Rotate List

Rotate List


今天是一道有關(guān)鏈表的題目,來自LeetCode,難度為Medium,Acceptance為22%。

題目如下

Given a list, rotate the list to the right by k places, where k is non-negative.
Example
Given 1->2->3->4->5 and k = 2,
return 4->5->1->2->3.

解題思路及代碼見閱讀原文

回復(fù)0000查看更多題目

解題思路

該題的思路較為簡單。

首先,回憶一下刪除倒數(shù)第k個(gè)節(jié)點(diǎn)的題目。用兩個(gè)指針,一個(gè)先走k步,然后一快一慢,直到快指針為null,慢指針指向的節(jié)點(diǎn)即為我們要刪除的節(jié)點(diǎn)。更多細(xì)節(jié)會在后續(xù)的題目中推送。

然后,該題的思路與之類似。即找到倒數(shù)第k個(gè)節(jié)點(diǎn),讓其next指向null。鏈表的最后一個(gè)節(jié)點(diǎn)指向表頭。

需要注意的是k一定是小于鏈表長度的,因此首先應(yīng)該將k對鏈表的長度取模。

下面是代碼

代碼如下

java版
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        // write your code here
        if(head == null || k <= 0)
            return head;
        k = k % getLength(head);
        if(k == 0)
            return head;
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0; i < k; i++) {
            fast = fast.next;
        }
        while(fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode result = slow.next;
        slow.next = null;
        fast.next = head;
        return result;
    }
    
    private int getLength(ListNode head) {
        int length = 0;
        while(head != null) {
            head = head.next;
            length++;
        }
        return length;
    }
}

關(guān)注我
該公眾號會每天推送常見面試題,包括解題思路是代碼,希望對找工作的同學(xué)有所幫助

image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容