【Leetcode】Leetcode143.重排链表

Leetcode143.重排链表

题目

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list

思路

用堆栈将链表保存,然后交替改变节点指向。需要注意奇偶数以及最后可能出现的野节点

代码

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

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if(not head):
            return
        s = []
        while(head):
            s.append(head)
            head = head.next
        i = 0
        j = len(s)-1
        while(i < j):
            s[i].next = s[j]
            i = i+1
            if(i==j):
                break
            s[j].next = s[i]
            j = j-1
        s[j].next = None

在这里插入图片描述

发布了97 篇原创文章 · 获赞 55 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/voidfaceless/article/details/103380712
今日推荐