Reverse a singly linked list.
解析:
/**
* 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* p1 = head, *p2 = head->next;
if ( head->next->next == NULL) {
p1->next = NULL;
p2->next = p1;
return p2;
}
ListNode* p3 = head->next->next;
p1->next = NULL;
do{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}while(p3!=NULL);
p2->next = p1;
return p2;
}
};