LeetCode: Reverse Nodes in k-Group
Title :
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
思路:问题并不难,关键是指针反转需要注意的一些细节。首先是往前走k步,如果这k步没有到头,要将中间的k个元素翻转。翻转也很简单,让每个后添加的作为头就行了。如果到头,就需要将后面的全部加到链表尾部,同时记住,这个地方要return,因为已经结束,不然无法跳出循环。
class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { // 向后查找k个元素,判断是否要进行翻转 if (head == NULL) return NULL; ListNode *t = head; for (int i = 0; i < k - 1; i++) { t = t -> next; if (t == NULL) return head; } // 否则就利用递归,先将之后的部分进行翻转 t = reverseKGroup(t -> next, k); // 然后再将前面这一部分翻转过来 ListNode *s; while (k --) { // 这部分反转的代码需要仔细注意 s = head; head = head -> next; s -> next = t; t = s; } // 返回新的序列 return t; } };
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.
思路:越简洁的代码越不容易出错。注意m=1的情况,q 指向m元素的前一个,p指向m元素
class Solution{ public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode* p = head,*q = NULL; int gap = n-m; while (--m > 0){ q = p; p = p->next; } ListNode* tail,*end; tail = end = p; p = p->next; while(gap--){ ListNode* t = p->next; p->next = tail; tail = p; p = t; } end->next = p; if (q == NULL) return tail; else q->next = tail; return head; } };