Reverse a singly linked list.
定义3个相邻的指针,pre、cur、post,每次往后挪一位,将cur的next指向pre,直到post为空。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* pre = head;
ListNode* cur = pre->next;
ListNode* post = cur->next;
pre->next = NULL;
while(post)
{
cur->next = pre;
pre = cur;
cur = post;
post = post->next;
}
cur->next = pre;
return cur;
}
};