LeetCode 061 Rotate List

来源:互联网 发布:淘宝lol代练可靠吗 编辑:程序博客网 时间:2024/05/01 20:06

题目


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.csdn.net/fightforyourdream/article/details/15332423




0 0
原创粉丝点击