[leetcode]61. Rotate List反轉鏈表k個節點

相似於找鏈表的後k個節點java

不一樣的是要把前邊的接到後邊指針

public ListNode rotateRight(ListNode head, int k) {
        //特殊狀況
        if (head==null||head.next==null||k==0) return head;
        int len = 0;
        ListNode p = head;
        //計算鏈表長度,防止k大於長度
        while (p!=null)
        {
            len++;
            p = p.next;
        }
        //k大於等於len的狀況
        k = k>=len?k%len:k;
        if (k==0) return head;
        //下邊是鏈表取後k個節點的方法,重要,雙指針
        p = head;
        while (k-->0)
        {
            p = p.next;
        }
        ListNode q = head;
        while (p.next!=null)
        {
            p = p.next;
            q = q.next;
        }
        //找到目標節點開始位置
        ListNode res = q.next;
        //將原鏈表斷開位置的後邊置爲null
        q.next=null;
        //將前邊的鏈表接上
        ListNode temp = res;
        while (temp.next!=null)
        {
            temp = temp.next;
        }
        temp.next = head;
        return res;
    }
相關文章
相關標籤/搜索