rotate list java_Rotate List leetcode java

题目:

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

题解:

这道题主要先理解题意,就是倒着数k个node,从那开始到结尾和之前那部分对调,那个例子就是,4->5拿前面来,1->2->3拿后面去。

几个特殊:

k是可以大于整个list的长度的,所以这时要对k对len取模

如果取模之后得0,相当于不用rotate,直接返回

处理完特殊情况后,就用熟悉的faster/slower双指针解决就好(看到这种linkedlist,倒着数数的,就条件反射了)

先对faster设步长为n,然后faster和slower再一起走,知道faster.next==null,说明slower指向要倒着数的开始点的前一个位置。

所以slow.next就是要返回的newhead,保存一下。

然后把faster.next接到head上,slower.next存为null,作队尾。

这样就把list给rotate了。

这是我想的一种解法,还有一种就是把整个list连起来,变成环,找到切分点断开就行。

解法1:

1    public ListNode rotateRight(ListNode head, int n) {

2         if(head==null||head.next==null||n==0)

3             return head;

4         ListNode fast = head, slow = head,countlen = head;

5         ListNode newhead = new ListNode(-1);

6         int len = 0;

7

8         while(countlen!=null){

9             len++;

10             countlen = countlen.next;

11         }

12

13         n = n%len;

14         if(n==0)

15             return head;

16

17         for(int i = 0; i 

18             fast = fast.next;

19

20         while(fast.next!=null){

21             slow = slow.next;

22             fast = fast.next;

23         }

24

25         newhead = slow.next;

26         fast.next = head;

27         slow.next = null;

28

29         return newhead;

30     }

解法2:

1 public ListNode rotateRight(ListNode head, int n) {

2

3     if (head == null || n == 0)

4         return head;

5     ListNode p = head;

6     int len = 1;//since p is already point to head7     while (p.next != null) {

8         len++;

9         p = p.next;

10     }

11     p.next = head; //form a loop12     n = n % len;

13     for (int i = 0; i 

14         p = p.next;

15     } //now p points to the prev of the new head16     head = p.next;

17     p.next = null;

18     return head;

19 }

Reference for 2: http://leetcodenotes.wordpress.com/2013/08/14/leetcode-rotate-list-%E6%8A%8A%E5%90%8Ek%E4%B8%AArotate%E5%88%B0list%E5%89%8D%E9%9D%A2%E5%8E%BB%EF%BC%8Ck%E5%8F%AF%E4%BB%A5%E8%B6%85%E8%BF%87list%E6%9C%AC%E8%BA%AB%E9%95%BF%E5%BA%A6/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值