Reverse Nodes in k-Group
2015-06-15 16:44
537 查看
题目:
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个节点的逆转,逆转方式采用头结点插入方式
代码:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k<=1||head==NULL || head->next==NULL) return head;
int len=0;
ListNode* p=head;
while(p)//计算总长度
{
len++;
p=p->next;
}
if(k>len) return head;
/*完成k个节点的逆转*/
p=head;
ListNode *pre=p;
ListNode *last=NULL;
ListNode *mark=p;//记录逆转链表的第一个节点,以便将其与后续链表连接起来
p=p->next;
int n=1;
while(n!=k&&p!=NULL)
{
last=p->next;
p->next=pre;
mark->next=last;
pre=p;
p=last;
n++;
}
if(len-k>=k)
mark->next=reverseKGroup(p,k);//递归调用
else
mark->next=p;
head=pre;
return head;
}
};
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个节点的逆转,逆转方式采用头结点插入方式
代码:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k<=1||head==NULL || head->next==NULL) return head;
int len=0;
ListNode* p=head;
while(p)//计算总长度
{
len++;
p=p->next;
}
if(k>len) return head;
/*完成k个节点的逆转*/
p=head;
ListNode *pre=p;
ListNode *last=NULL;
ListNode *mark=p;//记录逆转链表的第一个节点,以便将其与后续链表连接起来
p=p->next;
int n=1;
while(n!=k&&p!=NULL)
{
last=p->next;
p->next=pre;
mark->next=last;
pre=p;
p=last;
n++;
}
if(len-k>=k)
mark->next=reverseKGroup(p,k);//递归调用
else
mark->next=p;
head=pre;
return head;
}
};
相关文章推荐
- Node.js学习
- Node.js学习--基础知识(8)--全局对象和全局变量
- Hadoop 2.0 NameNode HA和Federation实践
- 【转】nodejs 模块加载
- Node.js学习--基础知识(5)--npm
- nodejs 中压缩/解压方案
- Angular Material串串学客户端开发 2 - Node.js模块加载机制Require()
- node.js 初体验
- Node.js+Yeoman构建前端自动化Web应用
- HDU 4587 Two Nodes、POJ 2375 Reliable Nets (Tarjan)
- Clone Graph Leetcode 133
- DOM Nodes
- leetcode--Populating Next Right Pointers in Each Node
- Swap Nodes in Pairs
- 文件系统(一)--super.c bitmap.c inode.c 源码分析
- Swap Nodes in Pairs
- 19 Remove Nth Node From End of List(去掉链表中倒数第n个节点Easy)
- 一晚上 -- Populating Next Right Pointers in Each Node II
- [Node.js] 对称加密、公钥加密和RSA
- Node.js学习--基础知识(4)--模块与包