61. Rotate List

来源:互联网 发布:java项目总结 编辑:程序博客网 时间:2024/06/09 16:44
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.

Subscribe to see which companies asked this question

My naive solution:

public class Solution {    public ListNode rotateRight(ListNode head, int k) {        if(head==null||head.next==null)            return head;        ListNode now=head;        int count=0;        while(now!=null){            count++;            now=now.next;        }        k%=count;        while(k--!=0){            now=head;            while(now.next.next!=null)                now=now.next;            now.next.next=head;            head=now.next;            now.next=null;        }        return head;            }}

Solution 2:

public class Solution {    public ListNode rotateRight(ListNode head, int k) {        if(head==null||head.next==null)            return head;        ListNode temp=head;        int count=1;        while(head.next!=null){            head=head.next;            count++;        }        head.next=temp;        k%=count;        head=temp;        for(int i=1;i<count-k;++i)            head=head.next;        temp=head.next;        head.next=null;        return temp;    }}



0 0
原创粉丝点击