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

Reverse Nodes in k-Group leetcode

2014-09-01 22:01 232 查看
Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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


首先,搞清楚怎么逆转一个单链表。其实O(n)就可以了。第一个肯定是last one。然后我们每遍历到一个node,就把它放到最链表的首位,


最后一个么,最后就成为第一个了。下面是一个简单逆转链表的程序。



ListNode* helper = new ListNode(0);
helper->next = head;
ListNode* pre = helper;
ListNode* last = head;
ListNode* cur = head->next;
while(cur != nullptr) {
last->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = last->next;
}
return helper->next;
因为有“放到链表首位”的操作,我们需要一个dummy的头节点,遇到的新节点我们simply state: pre.next = cur; 保持一个invariant就是last节点始终在最后(cur的前面一个)

然后我们有如下方法:

ListNode* reverseList(ListNode* pre,ListNode* next) {
ListNode* last = pre->next;
ListNode* cur = last->next;
while(cur != next) {
last->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = last->next;
}
return last;
}


就是区间的reverse。因为题目要求的是k group逆转嘛。注意人返回的是最后一个(last)节点,这样下一个k-group就可以用上了


ListNode *reverseKGroup(ListNode *head, int k) {
if(k<=1 || head == nullptr)
return head;
ListNode* helper = new ListNode(0);
helper->next = head;
ListNode* pre = helper;
int i = 0;
while(head != nullptr) {
i++;
if(i % k == 0) {
pre = reverseList(pre,head->next);
head = pre->next;
} else {
head = head->next;
}
}
return helper->next;
}

还有一个添加头结点的例子:链表的插入排序:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* helper = new ListNode(0);
helper->next = head;
ListNode* pre = helper;
ListNode* sortCur = helper->next;
ListNode* sortEnd = head;
ListNode* cur = head->next;
while(cur != nullptr) {
while(sortCur != cur && sortCur->val <= cur->val) {
pre = pre->next;
sortCur = sortCur->next;
}
if(sortCur == cur) {
sortEnd = cur;
} else {
sortEnd->next = cur->next;
cur->next = sortCur;
pre->next = cur;
}
cur = sortEnd->next;
pre = helper;
sortCur = helper->next;
}
head = helper->next;
delete helper;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表反转