Reverse Linked List

LeetCode #206


Description:

Reverse a singly linked list.

Example:

1->2->3->4->5

Idea:

set pre=NULL

pre curr
1. store curr->next into tmp
2. curr->next=pre
3. update pre and curr: pre=curr, curr=tmp

Code:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL || head->next==NULL) return head;

        ListNode *pre=nullptr, *curr=head;
        ListNode *tmp;

        while(curr!=NULL){
            tmp = curr->next;
            curr->next=pre;
            pre=curr;
            curr=tmp;
        }
        return pre;

    }
};

results matching ""

    No results matching ""