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

说明:

扫描二维码关注公众号,回复: 13457830 查看本文章

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

题解

算法思想:

  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)

猜你喜欢

转载自blog.csdn.net/wq_0708/article/details/121450987