1. Reverse Linked List
题目要求:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
初想用递归来实现应该会挺好的,但最终运行时间有点久,达到72ms,虽然没超时。具体程序如下:
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 */
1 ListNode* recurList(ListNode* p) 2 { 3 if (p->next != NULL) 4 { 5 ListNode* tmp = p->next; 6 if (tmp->next == NULL) 7 { 8 tmp->next = p; 9 p->next = NULL; 10 return tmp; 11 } 12 } 13 14 ListNode* ret = recurList(p->next); 15 ListNode* tmp = ret; 16 while (tmp->next != NULL) 17 tmp = tmp->next; 18 tmp->next = p; 19 p->next = NULL; 20 return ret; 21 } 22 23 ListNode* reverseList(ListNode* head) { 24 if (head == NULL || head->next == NULL) 25 return head; 26 27 ListNode* tail = recurList(head); 28 return tail; 29 }
在LeetCode论坛发现了一个8ms的解法,不得不为其简洁高效合彩!具体程序如下:
1 ListNode* reverseList(ListNode* head) { 2 ListNode *curr = head, *prev = nullptr; 3 while (curr) { 4 auto next = curr->next; 5 curr->next = prev; 6 prev = curr, curr = next; 7 } 8 return prev; 9 }
2. Reverse Linked List II
题目要求:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
该题的解法可以将一个链表分成三个部分,即1~m-1、m~n、n+1~最后一个元素3个部分,且仅对中间部分进行翻转,最后再将这3个部分合并。具体程序如下:
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* reverseBetween(ListNode* head, int m, int n) { 12 if(!head || !head->next || m >= n) 13 return head; 14 15 ListNode *start = head; 16 ListNode *preList = nullptr, *postList = nullptr; 17 18 int k = 1; 19 while(k < m) 20 { 21 preList = start; 22 start = start->next; 23 k++; 24 } 25 26 ListNode *prev = nullptr; 27 while(k <= n) 28 { 29 if(k == n) 30 postList = start->next; 31 auto next = start->next; 32 start->next = prev; 33 prev = start; 34 start = next; 35 k++; 36 } 37 38 ListNode *end = prev; 39 while(end && end->next) 40 end = end->next; 41 42 if(preList) 43 preList->next = prev; 44 else 45 head = prev; 46 end->next = postList; 47 48 return head; 49 } 50 };