Leetcode練習(Python):鏈表類:第143題:重排鏈表:給定一個單鏈表 L:L0→L1→…→Ln-1→Ln , 將其重新排列后變為: L0→Ln→L1→Ln-1→L2→Ln-2→… 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。


題目:
重排鏈表:給定一個單鏈表 L:L0→L1→…→Ln-1→Ln , 將其重新排列后變為: L0→Ln→L1→Ln-1→L2→Ln-2→…  你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。 
思路:
使用了懶人做法,使用了棧,應該還有更好的方法,想到后做補充。
程序:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if not head:
            return None
        myStack = []
        index1 = head
        counter = 0
        while index1:
            myStack.append(index1)
            index1 = index1.next
            counter += 1
        num_rotate = counter // 2
        index2 = head
        while num_rotate:
            tmp_node = myStack.pop()
            tmp_node.next = index2.next
            index2.next = tmp_node
            index2 = tmp_node.next
            num_rotate -= 1
        index2.next = None


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM