Ejemplo n.º 1
0
def deleteDuplication(pHead):
    head = LinkedList.ListNode()
    head.next = pHead
    # 以后使用p代表前一个节点,q代表后一个节点
    # 当只需要一个节点操作,如遍历时,使用p
    # 当需要执行诸如删除操作时,使用p和q,删除q所指的节点就是讲p.next置为q.next
    p = head
    q = pHead

    # 遍历中,判断q是否为None即可
    # 由于这里需要比较q.next,所以判断q.next是否None即可
    while q.next:  #r
        if q.val != q.next.val:
            if q != p.next:
                p.next = q.next
            else:
                p = q

        q = q.next

    # 判断链表结尾是重复的问题
    if q != p.next:
        p.next = q.next

    return head.next
def merge_two_sorted_list(list1,list2):
    # Create placeholder for result
    dummy_head = tail = ll.ListNode()

    while list1 and list2:
        if list1.data < list2.data:
            tail.next_node, list1 = list1,list1.next_node

        else:
            tail.next_node, list2 = list2, list2.next_node

        tail = tail.next_node

    tail.next_node = list1 or list2
    return dummy_head.next_node
Ejemplo n.º 3
0
def reverse_sublist(linked_list, s, f):
    dummy_head = sublist_head = ll.ListNode(0, linked_list)

    # Sets sublist_head to node before s
    for _ in range(1, s):
        sublist_head = sublist_head.next_node

    # Sets sublist_itter to Node at s
    sublist_itter = sublist_head.next_node
    for _ in range(f - s):
        temp = sublist_itter.next_node
        sublist_itter.next_node = temp.next_node
        temp.next_node = sublist_head.next_node
        sublist_head.next_node = temp
    return dummy_head.next_node
Ejemplo n.º 4
0
def revrese_linked_list(head):
    nodes = []

    while head:
        nodes.append(head)
        head = head.next_node
    # Reset next_node to None to prevent last item looping on itself
    for node in nodes:
        node.next_node = None

    new_head = dummy_head = ll.ListNode(0)
    nodes = nodes[::-1]

    new_head.next_node = nodes[0]
    for i in range(len(nodes) - 1):
        nodes[i].next_node = nodes[i + 1]

    return dummy_head.next_node