问题理解在python中排序链表的合并

时间:2019-05-28 15:52:28

标签: python sorting data-structures merge

我下面的代码在python中合并了两个排序的链表。 我不明白的是,它将在什么时候将第二个列表的值添加到第一个列表中。 如果有人可以向我解释一下,我将不胜感激。

def merge_sorted(self, llist):
    # set p and q pointers to head nodes of list1 and list2 (both of p,q are objects of class Node)
    p = self.head
    q = llist.head
    s = None

    # if either of the two lists doesn't exist return out of function (no point of sorting)
    if not p:
         return
    if not q:
         return

    # if both head pointers exist:
    if p and q:
        #based on which header data being smaller set s to that one
        if p.data <= q.data:
            s = p
            p = s.next # move p to next element, can also write : p = p.next
        else:
            s = q
            q = s.next # move p to next element, can also write : q = q.next

        new_head = s

        # go through all elements of both lists (after p/q being updated)
        while p and q:
            if p.data <= q.data:
                # the p/q here is one item iterated ahead of when we set s = p/q
                s.next = p
                # then we move s one item ahead, it its next pointer
                s = p  # could also write s = s.next
                p = s.next # could also write p.next, we move p one item ahead

            else:
                s.next = q
                s = q # could also write s = s.next
                q = s.next # could also write p.next, we move p one item ahead

    # when you reach the end of the list in one of the lists, set s to whatever is left of the other list and finish merging   
        if not p:
            s.next = q

        if not q:
            s.next = p

        self.head = new_head

0 个答案:

没有答案