LeetCode 61. Rotate List
2016-04-24 17:33
246 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
AC代码如下:
ListNode* rotateRight(ListNode* head, int k)
{
if(head == NULL)
return head;
int length = 0;
ListNode *p = head;
while(p != NULL)
{
length++;
p=p->next;
}
k = k%length;
if( length == 1 || k == 0)
return head;
ListNode *q = head;
for(int i = 1;i < length - k;i++)
q = q->next;
ListNode *r = q->next;
ListNode *newHead = q->next;
while(r->next != NULL)
r = r->next;
r->next = head;
q ->next = NULL;
return newHead;
}几个要注意的小问题,
1.函数中传入的节点head就是第一个节点,而不是我们常说的含头结点的单链表的头结点。
2.K值的问题,K如果大于单链表的长度,则取其对单链表长度取余后的结果。
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
AC代码如下:
ListNode* rotateRight(ListNode* head, int k)
{
if(head == NULL)
return head;
int length = 0;
ListNode *p = head;
while(p != NULL)
{
length++;
p=p->next;
}
k = k%length;
if( length == 1 || k == 0)
return head;
ListNode *q = head;
for(int i = 1;i < length - k;i++)
q = q->next;
ListNode *r = q->next;
ListNode *newHead = q->next;
while(r->next != NULL)
r = r->next;
r->next = head;
q ->next = NULL;
return newHead;
}几个要注意的小问题,
1.函数中传入的节点head就是第一个节点,而不是我们常说的含头结点的单链表的头结点。
2.K值的问题,K如果大于单链表的长度,则取其对单链表长度取余后的结果。
相关文章推荐
- 原型图登录优化
- 解决nexus 设备 无法OTA
- C.Candy
- flume
- .NET实验7-1
- C++旅途 之 申请动态内存和释放
- uva 10036 Divisibility
- ZOJ 3946 Highway Project SPFA 两个限制条件
- 三维空间离散点构建面(matlab)
- (最优比率生成树 )POJ 2728
- 合并两个排序的链表
- 关键字-----static 、const、inline、volatile....
- min
- Python 文件夹及文件操作
- 构建之法阅读笔记03
- View事件体系之--View的滑动
- ac自动机
- Android apk 签名后程序无法安装的问题
- Balanced Lineup(线段树)
- hdu5672 String(尺取法)