美文网首页
双指针应用五:链表反转

双指针应用五:链表反转

作者: 程一刀 | 来源:发表于2021-05-10 09:41 被阅读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

    相关文章

      网友评论

          本文标题:双指针应用五:链表反转

          本文链接:https://www.haomeiwen.com/subject/htmudltx.html