Loop and cutting of linked lists
Package Level3; import Utility. listNode;/***** 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. **/public class S61 {public static void main (String [] args) {ListNode head = new ListNode (1); ListNode n2 = new ListNode (2 ); listNode n3 = new ListNode (3); ListNode n4 = New ListNode (4); ListNode n5 = new ListNode (5); head. next = n2; n2.next = n3; n3.next = n4; n4.next = n5; ListNode rotateHead = rotateRight (head, 2); rotateHead. print ();} public static ListNode rotateRight (ListNode head, int n) {if (head = null) {return null;} ListNode back = head; ListNode front = head; listNode end = head; // first change the linked list to a circular linked list while (front. next! = Null) {front = front. next;} end = front; // record the front of the original end node. next = head; // forming the ring front = head; // restore the front pointer // make the front n distances before the back for (int I = 0; I <n; I ++) {front = front. next;} // move the while (front! = End) {front = front. next; back = back. next;} ListNode rotateHead = back. next; // find the chain table header back after rotate. next = null; // The return rotateHead of the open loop linked list ;}}