60. 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.
---
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { // check if(head == null || head.next == null || n==0) return head; // find the lenth ListNode r = head; int len=0; while(r != null){ len++; r = r.next; } n = n % len; // check adjusted n if(n==0) return head; // find the kth ListNode s = head; ListNode f = head; while(n>0){ f = f.next; n--; } while(f.next != null){ s = s.next; f = f.next; } // rotate ListNode newHead = s.next; f.next = head; s.next = null; return newHead; } }
浙公网安备 33010602011771号