【Leetcode每日一题】143. 重排链表(转化成线性表)

Leetcode 每日一题
题目链接:143. 重排链表
解题思路: 将链表转化为线性表存储,然后通过下标进行重排。
题解:

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 head != None:
            node_list = []
            node = head
            while node != None:
                node_list.append(node)
                node = node.next
                
            node = head
            for i in range(int(len(node_list) - 1)):
                if i % 2 == 0:
                    node.next = node_list[-(int(i/2) + 1)]
                else:
                    node.next = node_list[int(i/2 + 1)]
                node = node.next
            node.next = None

猜你喜欢

转载自blog.csdn.net/qq_37753409/article/details/109178828