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

[LeetCode] Reverse Nodes in k-Group

2015-07-06 14:54 507 查看
Well, since the
head
pointer may also be modified, we create a
new_head
that points to it to facilitate the reverse process.

For the example list
1 -> 2 -> 3 -> 4 -> 5
in the problem statement, it will become
0 -> 1 -> 2 -> 3 -> 4 -> 5
(we init
new_head -> val
to be
0
). Then we set a pointer
pre
to
new_head
and another
cur
to
head
. Then we insert
cur -> next
after
pre
for
k - 1
times if the current node
cur
has at least
k
nodes after it (including itself). After reversing one
k
-group, we update
pre
to be
cur
and
cur
to be
pre-> next
to reverse the next
k
-group.

The code is as follows.

 class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!hasKNodes(head, k)) return head;
ListNode* new_head = new ListNode(0);
new_head -> next = head;
ListNode* pre= new_head;
ListNode* cur = head;
while (hasKNodes(cur, k)) {
for (int i = 0; i < k - 1; i++) {
ListNode* temp = pre-> next;
pre-> next = cur -> next;
cur -> next = cur -> next -> next;
pre-> next -> next = temp;
}
pre= cur;
cur = pre-> next;
}
return new_head -> next;
}
private:
bool hasKNodes(ListNode* node, int k) {
int cnt = 0;
while (node) {
cnt++;
if (cnt >= k) return true;
node = node -> next;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: