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:
For k = 2, you should return:
For k = 3, you should return:
题目大意:在一个链表中,每 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;
}
};
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;
}
};
相关文章推荐
- [C/C++]反转链表
- C#实现基于链表的内存记事本实例
- C#模拟链表数据结构的实例解析
- C#中Ilist与list的区别小结
- C#中IList<T>与List<T>的区别深入解析
- C#对list列表进行随机排序的方法
- Vc++ 控件List Control用法总结
- C++实现的泛型List类分享
- C语言实现带头结点的链表的创建、查找、插入、删除操作
- C++利用静态成员或类模板构建链表的方法讲解
- C++实现简单的学生管理系统
- C#使用IComparer自定义List类实现排序的方法
- C# Datagridview绑定List方法代码
- javascript radio list的实现细节(多浏览器兼容)
- c++ STL容器总结之:vertor与list的应用
- Linux内核链表实现过程
- C++链表倒序实现方法
- C#通过链表实现队列的方法
- C#实现的简单链表类实例
- java实现List中对象排序的方法