您的位置:首页 > Web前端 > Node.js

【LeetCode算法练习(C++)】Reverse Nodes in k-Group

2017-10-20 16:00 399 查看
题目:

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

链接:Reverse Nodes in k-Group

解法:设置虚拟头结点便于操作,每轮检查是否还有足够的节点可供转置,之后转化为链表转置问题。时间O(n)

class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (k < 2) return head;
ListNode* h = new ListNode(0);
h->next = head;
ListNode* p = h;
while (enoughNode(p, k)) {
ListNode* p1 = p->next;
ListNode* p2 = p1->next;
ListNode* p3 = p2->next;
ListNode* nxt = p;
for (int i = 0; i < k; i++) {
nxt = nxt->next;
}
p1->next = nxt->next;
nxt = p1;
for (int i = 0; i < k - 1; i++) {
p2->next = p1;
p1 = p2;
p2 = p3;
if (p3) p3 = p3->next;
}
p->next = p1;
p = nxt;
}
ListNode* tmp = h;
h = h->next;
delete(tmp);
return h;
}
bool enoughNode(ListNode* head, int k) {
for (int i = 0; i < k; i++) {
if (!head->next) return false;
head = head->next;
}
return true;
}
};


Runtime: 36 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: