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

Leetcode: Reverse Nodes in k-Group

2013-12-05 16:00 204 查看
仅允许使用常数时间, 交换 k-group 的节点

思路:

1. 完全逆转一个链表: 每遍历到一个节点, 就将该节点放在链表首位

2. 在(1) 的基础上添加大小为 j 的窗口

总结:

1. 看来上一道题目思路也不是最优的

代码: update

class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *newHead = new ListNode(0);
newHead->next = head;

int cnt = 0;
ListNode *cur_node = head;
ListNode *last_tail = newHead;
while(cur_node) {
cnt++;
if(cnt == k) {
ListNode *cp = cur_node->next;

cur_node->next = NULL;
last_tail = reverseList(last_tail->next, last_tail);
last_tail->next = cp;

cur_node = cp;
cnt = 0;
continue;
}
cur_node = cur_node->next;
}
return newHead->next;
}

ListNode *reverseList(ListNode*head, ListNode*last_tail) {
ListNode *next_node = head->next;
ListNode *res = head;
while(next_node) {
ListNode *tmp = next_node->next;
next_node->next = head;
head = next_node;
next_node = tmp;
}
last_tail->next = head;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: