leetcode:Rotate List
2016-07-05 22:17
363 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
开始没考虑k比链表长度大的情况,其实到现在我们不清楚为啥要考虑这种情况,难道是为了增加难度?
当k大于链表长度n时,相当于k=k%n;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k)
{
ListNode p1=head,p2=head;
if(k==0||head==null)
return head;
for(int i=0;i<k;i++)
{
p1=p1.next;
if(p1==null)
{
k=k%(i+1);
if(k!=0)
{
i=-1;
p1=head;
}
else
return head;
}
}
while(p1.next!=null)
{
p1=p1.next;
p2=p2.next;
}
ListNode newHead=p2.next;
p2.next=null;
p1.next=head;
return newHead;
}
}
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
开始没考虑k比链表长度大的情况,其实到现在我们不清楚为啥要考虑这种情况,难道是为了增加难度?
当k大于链表长度n时,相当于k=k%n;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k)
{
ListNode p1=head,p2=head;
if(k==0||head==null)
return head;
for(int i=0;i<k;i++)
{
p1=p1.next;
if(p1==null)
{
k=k%(i+1);
if(k!=0)
{
i=-1;
p1=head;
}
else
return head;
}
}
while(p1.next!=null)
{
p1=p1.next;
p2=p2.next;
}
ListNode newHead=p2.next;
p2.next=null;
p1.next=head;
return newHead;
}
}
相关文章推荐
- Java基础知识(一)
- centos7安装zabbix3.0.3
- tomcat 配置虚拟站点
- Cache应用中的服务过载案例研究
- Ubuntu入门学习笔记(1)
- Can you share some Scala List class examples?
- 类的继承和接口的实现
- pager-taglib分页中文乱码
- Python安装Pip出现的问题
- JSON详解
- 199_让PieChart出来之后动画
- 反人类的MyEclipse之-eclipse设置花括号换行显示
- 动态规划--背包问题
- BroadcastReceiver and Serivce
- 225. Implement Stack using Queues
- 【代班大咖第二期】我想聊聊高科技
- # ReactiveCocoa - 进阶篇
- 用户空间的spi驱动
- leetcode 232. Implement Queue using Stacks
- Spring之AOP专题报道(自己总结版)