【LeetCode】剑指 Offer II 024. 反转链表

/**
 * 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* dummy = new ListNode;
        ListNode* pre=nullptr,*temp=head;
        while(temp){
            dummy->next=temp;
            temp=temp->next;
            dummy->next->next=pre;
            pre=dummy->next;
        }
        return dummy->next;
    }
};

头插法插入节点

posted @ 2022-02-23 00:13  Jerry2km1  阅读(39)  评论(0)    收藏  举报