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

[Linked List]Reverse Nodes in k-Group

2015-12-12 16:01 609 查看
Total Accepted: 48614 Total Submissions: 185356 Difficulty: Hard

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


(M) Swap Nodes in Pairs

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode* newHead=NULL,*p=head,*next=NULL;
while(p){
next    = p->next;
p->next = newHead;
newHead = p;
p       = next;
}
return newHead;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(k<=1){
return head;
}
ListNode *pre=NULL,*next=NULL;
ListNode *cur=head;
ListNode *reverseHead = NULL;
int cnt = 0;
while(cur){
if(cnt==0){
reverseHead = cur;
}
next = cur->next;
++cnt;
if(cnt==k){
cur->next=NULL;
ListNode *newHead = reverseList(reverseHead);
pre ? pre->next = newHead : head=newHead;
reverseHead->next = next;
pre = reverseHead;
cur = next;
cnt = 0;
}else{
cur = cur->next;
}
}
return head;
}
};


Next challenges: (M) Rotate List (M) Reorder List (M) Sort List
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: