Title: Rotate List
Solution 1:
<span style= "FONT-SIZE:18PX;" >/**leetcode Rotate List:given A list, Rotate the list to the right by K places, where K is non-negative. * Title: Circular mobile Linked list, equivalent to the link list from the right number of K nodes moved to the front of the table * idea: Mobile is simple, the focus is to find the number of the countdown to the list of K, is equivalent to find the number of k+1 count, set two pointers, successively traverse the list, the middle of the number of K * When the previous pointer goes to the last node, the pointer at the back points to the count of K+1 * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * Next = Null *} *} * * Package Javatrain;public class Train14 {public ListNode rotateright (ListNode head, int k) {Listnod e Pfast,pslow,pknode; int n = 0; if (head = = NULL | | k < 1) return head;//Note special case pfast = head; Pslow = head; while (pfast! = null) {pfast = Pfast.next; n++; } k = k%n;//loop movement, can be converted to modulo if (k = = 0) return head;//The number of moves is equal to its own length, equivalent to itself pfast = head; while (k>0 && pfast! = null) {pfast = Pfast.next; k--; } WHILe (pfast.next! = null) {pfast = Pfast.next; Pslow = Pslow.next; } Pknode = pslow.next;//k+1 node, the second is to move to the previous node, pslow.next = null; Pfast.next = head;//The last node is at this point before the head junction return Pknode; }}</span>
Solution 2:
<span style= "FONT-SIZE:18PX;" >//Method 2: Linking the list to the ring, and then looking for new head node and tail nodes, that is, in the Len-k package Javatrain;public class Train14_1 {public ListNode rotateright ( ListNode Head, int k) {if (head = = NULL | | k = = 0) return head;//special case ListNode Pnode = Head;int len = 1;while (Pnode.next! = NULL) {pnode = pnode.next;len++;} K = Len-k%len;pnode.next = head;//Note At this point pnode is the original tail node for (int i = 0;i < k;i++) {pnode = Pnode.next;} Head = Pnode.next;pnode.next = Null;return head;}} </span>
"Leetcode" Rotate list circular link list