leetcode 61. Rotate List
2016-03-20 12:43
344 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (k == 0)
return head;
ListNode*p = head;
int len = 0;
while (p != NULL)
{
p = p->next;
len++;
}
if (len == 0||len==1)
return head;
k = k%len;
if (k == 0)
return head;
p = head; int kk = 1;
while (kk != len - k)
{
p = p->next;
kk++;
}
ListNode*p1 = p->next, *p2 = p->next;
while (p1->next != NULL)
p1 = p1->next;
p1->next = head;
p->next = NULL;
head = p2;
return head;
}
};
accepted
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (k == 0)
return head;
ListNode*p = head;
int len = 0;
while (p != NULL)
{
p = p->next;
len++;
}
if (len == 0||len==1)
return head;
k = k%len;
if (k == 0)
return head;
p = head; int kk = 1;
while (kk != len - k)
{
p = p->next;
kk++;
}
ListNode*p1 = p->next, *p2 = p->next;
while (p1->next != NULL)
p1 = p1->next;
p1->next = head;
p->next = NULL;
head = p2;
return head;
}
};
accepted
相关文章推荐
- Tomcat集群配置
- MySQL 01 通过二进制包安装MySQL
- 第三周项目1:求最大公约数
- 图的割点 邻接表和邻接矩阵的分析
- ASP.NET5 MVC6 连接SQLSERVER
- STS: Spring Boot and Hibernate
- 关键字void
- 每日一算法---寻找丑数
- React Native iOS环境搭建
- IOS Animation-贝塞尔曲线与Layer简单篇(一)
- hdu3608最长回文子串
- COGS 1584. [CTSC2007]挂缀
- Canvas小例子-时钟
- 多线程“基础篇”07之 线程休眠
- 第4周项目3(2)小学生算数能力测试系统
- mac上使用自带svn
- 线程控制 - AfxBeginThread工作者线程的封装类
- 软件包管理之源码编译安装
- git学习笔记
- Linux命令之 find