这是两道题。
24. Swap Nodes in Pairs : 把链表两两相邻的结点互换值。
25. Reverse Nodes in k-Group: 把链表中每k个结点组成的子链表翻转。
其实24就是25在k=2时候的情况。
就只讲25吧。
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked 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
这里说,只能用常数空间,而且不能改动结点里的值。那就只能改变node的next域,用人话说就是必须把指针翻转了。206. Reverse Linked List 这道题就是翻转整个链表的,我的博客在这里。
不多说了,上代码和注释。
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (needReverseSubList(head, k)) {
//首先把翻转最开始的k个节点
ListNode* nextGroupHead = head;
ListNode* headForAll = reverseSubList(head, k, nextGroupHead); // headForAll是整个链表的新的头结点
ListNode* tail = head; // tail记录子链表翻转后的尾节点(要和下一个子链表翻转后的头结点相连)
while (needReverseSubList(nextGroupHead, k)) {
head = nextGroupHead;
ListNode* newSubHead = reverseSubList(head, k, nextGroupHead);
tail->next = newSubHead;
tail = head;
}
tail->next = nextGroupHead;
return headForAll;
}
else {
return head;
}
}
private:
// 函数:判断从p开始,还够不够k个结点。够则说明需要翻转,不够则不翻转
bool needReverseSubList(ListNode* p, int k) {
int count = 0;
while (p != NULL) {
count++;
p = p->next;
}
return count >= k;
}
// 函数:翻转从head开始的k个结点组成的子链表
// 返回的值是这个子链表翻转后的头结点
// nextGroupHead参数记录了下一个子链表原本的头结点
ListNode* reverseSubList(ListNode* head, int k, ListNode*& nextGroupHead) {
if (head == NULL || head->next == NULL) {
nextGroupHead = NULL;
return head;
}
ListNode *p = head;
ListNode *q = head->next;
ListNode *r = head->next->next;
head->next = NULL;
int count = 0;
while (++count < k) {
q->next = p;
p = q;
q = r;
if (r != NULL)
r = r->next;
else
break;
};
nextGroupHead = q;
return p;
}
};