双指针应用五:链表反转

2021-05-10  本文已影响0人  程一刀

题目地址: https://leetcode-cn.com/problems/reverse-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 *cur = head;
        ListNode *pre = nullptr;
        ListNode *temp = nullptr;
        while (cur) {
            temp =  cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return  pre;
    }
};

参考链接: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0206.%E7%BF%BB%E8%BD%AC%E9%93%BE%E8%A1%A8.md

上一篇 下一篇

猜你喜欢

热点阅读