算法:链表的奇偶位重排

链表的奇偶位重排

拟人算法系列文章,以容易理解的方式描述算法,点赞收藏不迷路

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def oddEvenList(self, head):
        index = 1
        dummy1 = ListNode(-1)
        dummy2 = ListNode(-1)

        cur1 = dummy1
        cur2 = dummy2

        while head:
            # 分别挂载在不同的链表上即可
            if index % 2 == 1:
                cur1.next = head
                cur1 = cur1.next
            else:
                cur2.next = head
                cur2 = cur2.next
            index += 1
            head = head.next

        # 偶链表的next节点赋值null,奇链表的末尾链接偶链表的头
        cur2.next = None
        cur1.next = dummy2.next

        return dummy1.next


if __name__ == '__main__':
    head = ListNode(1)
    head.next = ListNode(2)
    head.next.next = ListNode(3)
    head.next.next.next = ListNode(4)
    head.next.next.next.next = ListNode(5)

    s = Solution()
    new_head = s.oddEvenList(head)

    while new_head:
        print(new_head.val, end=' ')
        new_head = new_head.next

    # 1 3 5 2 4

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值