微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

力扣 206. 反转链表

力扣 206. 反转链表

链接

思路

1、先引入一个数组,然后转置数组,再把数组赋值给链表
2、尾插法遍历旧链表,头插法建立新链表

代码1

/**
 * DeFinition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* l1 = head;
        vector <int> vec;
        while(l1){
            vec.push_back(l1->val);
            l1 = l1->next;
        }
        reverse(vec.begin(),vec.end());
        l1 = head;
        int i = 0;
        while(l1){
            l1->val = vec[i];
            l1 = l1->next;
            i++;
        }
        return head;
    }
};

代码2

/**
 * DeFinition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* l1;
        l1 = head;
        ListNode* l2=nullptr;
        if(l1){
            l2 = new ListNode;
            l2->val = l1->val;
            l1 = l1->next;
        }
        while(l1){
            ListNode* l3 = new ListNode;
            l3->val = l1->val;
            l3->next=l2;
            l2 = l3;
            l1= l1->next;
        }
        return l2;
    }
};

代码随想录方法

//双指针法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* temp; // 保存cur的下一个节点
        ListNode* cur = head;
        ListNode* pre = NULL;
        while(cur) {
            temp = cur->next;  // 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur->next = pre; // 翻转操作
            // 更新pre 和 cur指针
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

在这里插入图片描述

原文地址:https://www.jb51.cc/wenti/3287902.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐