0
点赞
收藏
分享

微信扫一扫

leetcode-206-反转链表

雪域迷影 2022-03-15 阅读 38

https://leetcode-cn.com/problems/reverse-linked-list/

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


#include <iostream>
using namespace std;
struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL){}
};
// 时间复杂度O(n)
// 空间复杂度O(1)
class Solution{
public:
    ListNode* reverseList(ListNode *head){
        ListNode* pre = NULL;
        ListNode* cur = head;
        while (cur != NULL){
            ListNode* next = cur->next;
            // 上面是初始化三个指向
            // 进行反转
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        //  null <- 1 <- 3  -> 5 -> 7 -> null
        return pre;
    }
};

//  1 -> 3  -> 5 -> 7 -> null
// pre    cur  next
// null -> 1 -> 3  -> 5 -> 7
// 1
// pre指向 1  cur指向 1  next指向3
// null -> 1 -> 3  -> 5 -> 7
// 2
// pre指向 1  cur指向 3  next指向3
// null -> 1 -> 3  -> 5 -> 7
// 3
// pre指向 1  cur指向 3  next指向5
// null -> 1 -> 3  -> 5 -> 7
// 进行反转1
// null <- 1 -> 3  -> 5 -> 7
// 进行反转2
// null <- 1 <- 3  -> 5 -> 7

//                     pre指向 7  cur指向   next指向
//    1<- 3 <- 5 <- 7

int main (){
    // 创建链表
    ListNode n1(1);
    ListNode n2(3);
    ListNode n3(5);
    ListNode n4(7);
    ListNode n5(9);

    n1.next = &n2;
    n2.next = &n3;
    n3.next = &n4;
    n4.next = &n5;
    // 遍历
    ListNode *head = &n1;
    while (head){
        cout<< head->val<<"->";
        head = head->next;
    }
    cout<<endl;
    cout<<"---------"<<endl;
    //  翻转链表
    Solution solution;
    ListNode* res = solution.reverseList(&n1);

    while (res){
        cout<< res->val<<"->";
        res = res->next;
    }



    return 0;
}

举报

相关推荐

0 条评论