Leetcode #328:奇偶链表

Leetcode #328:奇偶链表

题干

该问题奇偶链表 题面:

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1) extra space complexity and O(n) time complexity.

给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。

示例

示例 1:

输入: 1->2->3->4->5->NULL
输出: 1->3->5->2->4->NULL

示例 2:

输入: 2->1->3->5->6->4->7->NULL
输出: 2->3->6->7->1->5->4->NULL

说明:

应当保持奇数节点和偶数节点的相对顺序。
链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。

题解

算法思想:

  1. 根据奇偶数原则,首先将odd指向head,even指向head.next,临时变量t指向head.next来保存第一个偶数节点以便最后拼接。
  2. odd、even分别交替指向下一个节点,即奇数节点连接奇数节点,偶数节点连接偶数节点。
  3. 最后只需将奇数尾部节点与偶数头部节点连接以拼接奇偶链表。

参考Leetcode #83:删除排序链表中的重复元素

Python

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

class Solution:
    @classmethod
    def oddEvenList(self,head:ListNode) -> ListNode:
        if head == None or head.next == None:
            return head

        odd = head
        even = head.next
        t = even
        while even != None and even.next != None:
            odd.next = even.next
            odd = odd.next
            even.next = odd.next
            even = even.next
        odd.next = t
        return head

def Link(x:list):
    """
    创建链表
    """
    n = len(x)
    nodes = []
    for i in range(n):
        if x[i]:  # 链表以None结尾
            node = ListNode(x[i])
            nodes.append(node)
            if i>0:
                nodes[i-1].next = nodes[i]
        else:
            return nodes[0]

if __name__ == "__main__":
    l1 = Link([1,2,3,4,5,None])
    l2 = Link([2,1,3,5,6,4,7,None])
    l_r= Solution.oddEvenList(l2)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值