LeetCode 061 Rotate List

本文介绍了一种链表旋转算法,该算法将链表向右旋转k个位置,并提供了详细的实现步骤与代码示例。

题目


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个节点,来旋转链表。

思路


1  基本思路。普遍使用的dummynode ,还有pre,cur 两个来表示前后节点。一开始先test往后k格;之后cur和test同时移动,当test为null时,cur即为新的头节点。此时要做些操作,pre.next要为null,新的head为cur。之后到链表最后,接上原来的头节点即可,dummynode发挥用处。代码如下:

public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if(n<=0 || head == null|| head.next==null) {
            return head;
        }
        ListNode dummynode = new ListNode(Integer.MIN_VALUE);
        dummynode.next = head;
        ListNode test =head;
        while(n>0){
            if(test==null){
                test=head;
            }
            test=test.next;
            n--;
        }
        
        ListNode  pre = dummynode;
        ListNode  cur = head;
        while(test!=null){
            pre=cur;
            cur=cur.next;
            test=test.next;
        }
        head=cur;
        pre.next=null;
        while(cur!=null){
            pre=cur;
            cur=cur.next;
        }
        pre.next=dummynode.next;
        return head;
    }
}



细节


1 极限情况要考虑好,比如head 为null 以及n<=0;

2 这个k的值如果超过链表大小怎么办,我一开始认为不可能,所以没有处理,结果不通过。面试的时候,任何细节都要提问弄清楚。之后就认为相当于取余的处理,通过。

3 之后看了另外一篇处理方式很有意思,先首尾相连再处理的方式,这里直接链接。

http://blog.youkuaiyun.com/fightforyourdream/article/details/15332423




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值