LEETCODE 25. Reverse Nodes in k-Group
题目大意
给出一个链表并给出一个正整数k,将链表中长度为k的子链表的节点顺序都弄反,其中k是小于等一链表长度的,如果最后那一段子链表长度不够k就不用管。
例如:
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
解题思路
也是用一个dummy node,每次将子链表反序之后就拼起来。
实现代码
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *dummyPtr = new ListNode(0);
ListNode *lastPtr = dummyPtr, *iterPtr = head;
dummyPtr->next = head;
while (iterPtr && k > 1) {
int counter = k;
while (counter && iterPtr) {
iterPtr = iterPtr->next;
counter--;
}
if (counter) {
return dummyPtr->next;
} else {
ListNode *curPtr = lastPtr->next, *nextPtr = curPtr->next;
while (nextPtr != iterPtr) {
ListNode *temp = nextPtr->next;
nextPtr->next = curPtr;
curPtr = nextPtr;
nextPtr = temp;
}
ListNode *temp = lastPtr->next;
lastPtr->next->next = iterPtr;
lastPtr->next = curPtr;
lastPtr = temp;
}
}
return dummyPtr->next;
}
};