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.

思考:用兩個指針A,B,A先走k步,然後A、B同時

想法

  • 1、A先走k步,然後A、B同時,直到A到表尾
  • 2、head指向B的next;
  • 3、將A的next指向表頭,B的next置爲null;

代碼

public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        ListNode first = head;
        ListNode second = head;

        if(head == null || head.next == null)
            return head;

        int sum = 0;

        while(k > 0){
            first = first.next;
            sum++;
            k--;
            if(first == null){
                first = head;
                k = k % sum;
            }

        }

        while(first.next != null){
            first = first.next;
            second = second.next;
            if(second == null)
                second = head;
        }

        first.next = head;
        head = second.next;
        second.next = null;

        return head;
    }
}
發佈了29 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章