LeetCode--206.翻转链表(C++)

力扣链接

本题采用双指针法,递归的方法后面在学习。下面的代码中给出了完整注释和主函数。

思路:

        定义一个cur指针初始指向头节点,定义一个pre指针初始指向空,cur先向后移动一个位置,接着pre跟着向后移动一个位置。此外定义一个temp临时指针用于保存cur的下一个节点便于cur指针向后移动。在while循环中执行翻转操作,最后pre指针指向最后一个节点,也即是翻转链表后的头节点。

//
// Created by lwj on 2023-03-26.
//

#include <iostream>

using namespace std;

// 定义链表节点
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int val) : val(val), next(NULL) {}
};

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* temp; // 保存cur的下一个节点
        ListNode* cur = head;
        ListNode* pre = NULL; // pre最后是翻转后的链表的头节点
        while(cur) {
            temp = cur->next;  // 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur->next = pre; // 翻转操作
            // 更新pre 和 cur指针
            pre = cur;
            cur = temp; //这个过程不理解的话看下b站代码随想录Carl大哥的讲解。 https://www.bilibili.com/video/BV1nB4y1i7eL/?vd_source=0b54aac40949e1acd0999c9785eedcfc
        }
        return pre;
    }
};

// 创建链表
ListNode* createList(int arr[], int n) {
    if (n == 0) {
        return NULL;
    }

    ListNode* head = new ListNode(arr[0]);
    ListNode* cur = head;
    for (int i = 1; i < n; i++) {
        cur->next = new ListNode(arr[i]);
        cur = cur->next;
    }

    return head;
}

// 打印链表
void printList(ListNode* head) {
    ListNode* cur = head;
    while (cur != NULL) {
        cout << cur->val << " ";
        cur = cur->next;
    }
    cout << endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(int);
//    cout << n <<endl;
    ListNode* head = createList(arr, n);

    Solution solution;
    ListNode* newHead = solution.reverseList(head);
    printList(newHead);

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值