LSGO——LeetCode實戰(數組系列): 61題 旋轉鏈表 (Rotate List)

原題:

給定一個鏈表,旋轉鏈表,將鏈表每個節點向右移動 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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/rotate-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解法一:

思路:這個題目存在一個規律。當我們向移動K個位置的時候,其實就是將鏈表前(length - k)個節點整體移接到鏈表的最後。
下面這個程序就是這個思想,找出第length - k的位置,直接將鏈表切成兩段再拼接。

程序一

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head == None:
            return None
        pre = ListNode(0)
        pre.next = head
        length = 1
        ans = head
        while ans.next != None:
            ans = ans.next
            length += 1
        k = k % length
        if k == length or k == 0:
            return head
        for i in range(length - k):
            pre =pre.next
        tail = new_head = pre.next
        pre.next = None
        while tail.next != None:
            tail = tail.next
        tail.next = head
        head = new_head
        return head

程序二:

程序二相對程序一,最大的不同是將鏈表變爲了循環鏈表,所以在鏈表的分割上會更爲便捷一些。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head == None or k==0 or head.next == None:return head
        length = 0
        temp = head
        while temp:
            temp = temp.next
            length +=1
        k = k % length
        temp = head
        for i in range(length-1):
            temp =  temp.next
        temp.next = head  # 形成了一個閉環
        temp =  head 
        for i in range(length -k):
            temp = temp.next
        head = temp
        for i in range(length-1):
            temp = temp.next
        temp.next = None
        return head
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章