题目描述:(链接)
Reverse a singly linked list.
解题思路:
链表真讨厌,总是出错。头插法。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseList(ListNode* head) { 12 if (head == NULL ) return head; 13 14 ListNode dummy(-1); 15 dummy.next = head; 16 17 ListNode *prev = dummy.next; 18 ListNode *cur = prev->next; 19 while (cur != NULL) { 20 prev->next = cur->next; 21 cur->next = dummy.next; 22 dummy.next = cur; 23 cur = prev->next; 24 } 25 26 return dummy.next; 27 } 28 };