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

25. Reverse Nodes in k-Group

2016-05-26 13:14 603 查看
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

题目大意:在一个链表中,每 k
个结点逆置,若剩余不足 k
个结点则不发生逆置
题目分析:因为逆置,很容易想到用。也可以使用把结点删除,再插入到前面的方法,不过要先判断剩余有没有k个。
代码如下(28ms):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode h(0);
h.next=head;
ListNode *pre=&h, *begin=&h, *end;
//pre表示遍历结点的前一个结点
//begin表示要逆置k个结点的前一个结点,end表示要逆置k个结点的后一个结点
stack<ListNode*> s;
while(pre->next){//不足k个进栈
if(k!=s.size()){
s.push(pre->next);
pre=pre->next;
}else{//有k个了就逆置
end=pre->next;//记录本次end
pre=begin;
while(!s.empty()){
pre->next=s.top();
s.pop();
pre=pre->next;
}
begin=pre;//记录下次begin
pre->next=end;//连起来
}
}
return h.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode 链表 list stack