力扣 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;
    }
};

在这里插入图片描述

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...