2015.5.6 05:04
Reverse a singly linked list.
Solution:
Too old.
Accepted code:
1 // 1CE, 1AC, not perfect 2 /** 3 * Definition for singly-linked list. 4 * struct ListNode { 5 * int val; 6 * ListNode *next; 7 * ListNode(int x) : val(x), next(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 ListNode* reverseList(ListNode* head) { 13 if (head == NULL) { 14 return NULL; 15 } 16 17 ListNode *p1 = head; 18 ListNode *p2 = p1->next; 19 p1->next = NULL; 20 ListNode *p3; 21 while (p2 != NULL) { 22 p3 = p2->next; 23 p2->next = p1; 24 p1 = p2; 25 p2 = p3; 26 } 27 return p1; 28 } 29 };