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.


1. 首先,需要先遍歷一遍拿到這個list的長度,順便把最後一個元素的next指向第一個head,做成一個循環鏈表。


2. 第二遍遍歷,走到第length-k個元素,記錄下下一個元素爲要返回的元素,然後把這個元素的next設置爲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) {
        if(n==0||head==null){
            return head;
        }
        // get length
        int length = 0;
        ListNode cursor = head;
        ListNode tail = null;
        while(cursor!=null){
            length++;
            tail = cursor;
            cursor = cursor.next;
        }
        n = n%length;
        tail.next = head;
        int i=0;
        cursor = head;
        while(i<length-n){
            tail = cursor;
            cursor = cursor.next;
            i++;
        }
        tail.next=null;
          
        return cursor;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章