61- rotating list

Highlights:

1, the number of calculations of the rotation rot = k% len

2, chain link head to tail constitute cycling conditions, in order to output a complete circular list

3, the head pointers are put a certain number of traverse, to find the head and tail, the tail of the link and then the next element is disconnected and the formation of a single linked list.

. 1  public ListNode RotateRight (ListNode head, int K) {
 2      IF (head == null || K == 0 ) {
 . 3          return head;
 . 4      }
 . 5      ListNode Cursor = head;
 . 6      ListNode tail = null ; // tail pointer 
7      int length = . 1 ;
 . 8      the while (! cursor.next = null ) // cycle to give a total length 
. 9      {
 10          Cursor = cursor.next;
 . 11          length ++;
 12 is      }
 13 is      int Loop Length-= (length K%); // number of cycles to obtain the 
14      tail = Cursor; // point to the end node 
15      cursor.next = head; // into the circular list 
16      Cursor = head; // points to the first node 
. 17      for ( int I = 0 ; I <loop; I ++) { // begin loop 
18 is          Cursor = cursor.next;
 . 19          tail = tail.next;
 20 is      }
 21 is      tail.next = null ; // into a single chain 
22 is      returnCursor; // return the current head 
23 }
View Code

 

Guess you like

Origin www.cnblogs.com/nxnslc-blog/p/12448101.html