萌新练习写代码的每日一练:重排链表

给定一个单链表 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.

思路:1、创建一个空数组num,遍历链表并将链表的值放入数组中,然后根据数组的下标重新取值

2、(学长提供)先用快慢指针找到链表中点,然后对后半部分做链表逆序,最后把前后两段链表合并

第二种我有点不太行,便尝试了第一种

代码:

class Solution:

    def reorderList(self, head: ListNode) -> None:

        """

        Do not return anything, modify head in-place instead.

        """

        if not head or not head.next:

            return head

            

        num = []

        while head is not None:

            num.append(head)

            head = head.next

        count = len(num)

        for i in range(count//2):

            # print(num[i])

            num[i].next = num[-1-i]

            num[-1-i].next = num[i+1]

            num[i+1].next = None

            

        return num[0]

中间遇到的问题:一开始做的是count/2,这样很容易溢出,就改成了count//2(向下取整防止溢出)。另一个问题虽然不太懂是为什么,一开始我是这么写的

dummy = ListNode()
        dummy.next = head
        cur = dummy
        while cur is not None:
            num.append(cur)
            cur = cur.next

放上去一直会出现问题,后来直接用head就ok了。

和师兄讨论时想到的新方法:使用栈和队列做,一开始的步骤也是放到数组里,后面的操作是利用一个标识符pos=1,将第一个数放到栈,pos取反;第二个数放到队列,pos取反;第三个数放到栈,pos取反,以此类推,重构链表的时候直接按新链表的顺序取数即可,代码如下:

def reorderList(head: ListNode) -> None:
    """
    Do not return anything, modify head in-place instead.
    """
    num = []
    while head:
        num.append(head.val)
        head = head.next
    pos = 1
    head = ListNode(0)
    dummy = head
    # print(num)
    while num:
        # print(count)

        if pos:
            val = num.pop(0)
            # print(val)
            head.next = ListNode(val)
        else:
            val = num.pop(-1)
            # print(val)
            head.next = ListNode(val)
        print(head.val)
        head = head.next
        pos = bool(1 - pos)
    return dummy.next

但是这个方法在LeetCode上有问题,在自己的编译器上就没问题,目前还在和师兄讨论中www。

题目来自LeetCode第143题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值