LeetCode題:旋轉鏈表

 
原題:
給定一個鏈表,旋轉鏈表,將鏈表每一個節點向右移動 k 個位置,其中 k 是非負數。
示例 1:
輸入: 1->2->3->4->5->NULL, k = 2
輸出: 4->5->1->2->3->NULL
解釋:
向右旋轉 1 步: 5->1->2->3->4->NULL
向右旋轉 2 步: 4->5->1->2->3->NULL

示例 2:
輸入: 0->1->2->NULL, k = 4
輸出: 2->0->1->NULL
解釋:
向右旋轉 1 步: 2->0->1->NULL
向右旋轉 2 步: 1->2->0->NULL
向右旋轉 3 步: 0->1->2->NULL
向右旋轉 4 步: 2->0->1->NULL
解法:其實從題目中就包含了解題思路,「旋轉」,是否是必須有一個環才能旋轉。思路:先把單向鏈表變成循環鏈表,而後旋轉之,找到新的頭節點,再把頭結點的上一個節點的next指向null,這樣,就把循環鏈表斷開了,獲得新的鏈表。
/** * 旋轉鏈表 * * @param head * @param k * @return */public ListNode rotateRight(ListNode head, int k) {    if (head == null) {        return null;    }    ListNode current = head;    //鏈表長度    int length = 1;    while (current.next != null) {        current = current.next;        length += 1;    }    //變成循環鏈表    current.next = head;    //新的頭結點的位置    int index = (length - (k % length));    if (index == 0) {        return head;    }    current = head;    //找到新的頭結點    for (int i = 0; i < index - 1; i++) {        current = current.next;    }    head = current.next;    //斷開鏈表    current.next = null;    return head;}
相關文章
相關標籤/搜索