【18】206. Reverse Linked List
206. Reverse Linked List
- Total Accepted: 188250
- Total Submissions: 429719
- Difficulty: Easy
- Contributors: Admin
Reverse a singly linked list.
Solution 1: Iterative
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 || head -> next == NULL) return head; 13 ListNode* dummy = new ListNode(-1); 14 dummy -> next = head; 15 /*time limitation 16 ListNode* next = head -> next; 17 while(next){//head节点是不变的,所以用next节点来判断 18 dummy -> next = next;//把next节点一直连在开头 19 head -> next = next -> next; 20 next -> next = dummy -> next; 21 next = head -> next;//next节点一直待在head后面 22 }*/ 23 24 ListNode* cur = head; 25 while(cur -> next){ 26 ListNode* tmp = cur -> next; 27 cur -> next = tmp -> next; 28 tmp -> next = dummy -> next; 29 dummy -> next = tmp; 30 } 31 32 return dummy -> next; 33 } 34 };
Solution 2: Recursive
递归解法的思路是,首先进入递归函数 不断递归,直到head指向最后一个节点。而p指向之前一个节点,调换head和p的位置,然后返回上一层递归函数,再交换p和head的位置,每次交换后,head节点后面都是交换好的顺序,直到p为首节点,然后再交换,首节点就成了为节点,此时整个链表也完成了翻转。
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 || head -> next == NULL) return head; 13 ListNode* p = head; 14 head = reverseList(p -> next); 15 p -> next -> next = p; 16 p -> next = NULL; 17 return head; 18 } 19 };