【问题标题】:Partition linked list around a value x : Cracking the coding Interview book围绕值 x 的分区链表:破解编码面试书
【发布时间】:2016-05-19 07:33:01
【问题描述】:

我正在尝试解决一个面试问题,使得给定的链表需要围绕一个值“x”进行分区。我尝试了一下,但没有得到想要的结果。

class Node(object):
    def __init__(self, val):
        self.val = val
        self.next = None

def Partition(head, x):
    x_node = Node(x)
    x_node.next = head
    current = head
    last = x_node
    while current:
        if current.val < x_node.val:
            last = last.next
            temp_val = current.val
            current.val = last.val
            last.val = temp_val
        current = current.next
    temp_val = last.val
    last.val = x_node.val
    x_node.val = temp_val

Partition(head,3)

Input:           1->4->3->2->5->2
Actual Output:   1->2->3->4->5->3
Expected Output: 1->2->2->3->4->5

提前致谢。

【问题讨论】:

  • 这实际上应该排序,还是只是分区?因为我认为预期的输出没有理由将 3 放在 4 之前。
  • 另外,这段代码是在交换值,而不是节点,这可能违反了练习的精神;在 Python 中,当然,交换单个值和节点引用是等价的成本,但链表的全部意义在于您可以重新排列节点而无需更改节点链接以外的任何内容。
  • @ShahdowRanger 分区。另外,您能否举例说明您的第二条评论。谢谢!

标签: python algorithm linked-list


【解决方案1】:

对于 [9,2,9,3,5,8,5,10,2,1](我在幕后神奇地转换为 ll),我得到 1,2,3,2, 9,9,5,8,5,10 的值为 5。

问题是让所有小于或等于该值的项的左侧的所有项都小于该值,其中该值本身可以出现在右侧分区中的任何位置。通知 9 出现在 5 之前,这与预期一致。

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

def partition(node, val):
b_n = node
head = node
right = False
while node:
    if node.data < val:
        if node == head:
            node = node.next
        else:
            head = Node(node.data, head)
            b_n.next = node.next
    else:
        right = True
        if right:
            r_e = node
    b_n = node
    node = node.next
r_e.next = None
return head

ll5 = Linked_List()
ll5.build_from_list([9,2,9,3,5,8,5,10,2,1])
ll6.head = partition(ll5.head, 5)
ll6.iterate()

.build_from_list() 和 .iterate() 是我在 Linked_List() 类中内置的方法。

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2018-11-21
    • 2013-09-05
    • 1970-01-01
    • 2015-12-06
    相关资源
    最近更新 更多