搜索此博客

2012年10月16日星期二

Rotate List

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.
The idea is to find the start node of the notation, the new head. This is done by counting the nodes until k. Note: Don't forget that k might be larger than the number of nodes in the linked list. If so, we need to use  the remainder of the mod of the length of the linked list, instead of k itself.
01 public ListNode rotateRight(ListNode head, int n) {
02     int len=0;
03     ListNode node=head;
04     //calculate length
05     while(node!=null)
06     {
07         len++;
08         node=node.next;
09     }
10     if(len<=1)
11         return head;
12     n=n%len;
13     if(n==0)
14         return head;
15   
16     ListNode first=head;
17     while(n-->0)
18     {
19         first=first.next;
20     }
21   
22     ListNode second=head;
23   
24     while(first!=null && first.next!=null)
25     {
26         first=first.next;
27         second=second.next;
28     }
29   
30     ListNode newHead=second.next;
31     second.next=null;
32     first.next=head;  
33     return newHead;      
34 }

没有评论:

发表评论