算法:旋转链表
定一個鏈表,旋轉鏈表,將鏈表每個節點向右移動?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?
將每個節點向后移動k個位置
class Solution {public ListNode rotateRight(ListNode head, int k) {if (head == null) return null;if (head.next == null) return head;ListNode old_tail = head;int n;//先將鏈表連成環for(n = 1; old_tail.next != null; n++)old_tail = old_tail.next;old_tail.next = head;//在根據K和鏈表長度在指定位置斷開鏈表ListNode new_tail = head;for (int i = 0; i < n - k % n - 1; i++)new_tail = new_tail.next;ListNode new_head = new_tail.next;new_tail.next = null;return new_head;} }鏈接:https://leetcode-cn.com/problems/rotate-list/solution/xuan-zhuan-lian-biao-by-leetcode/
總結