1.2从链表中移除重复项

无序链表移除重复项

# -*-coding:utf-8-*-
class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


def print_link(head):
    cur = head.next
    while cur.next != None:
        print(cur.data, end=' ')
        cur = cur.next
    print(cur.data)


def delete_rep(head):
    flag = set()
    pre = head
    cur = head.next
    while pre.next != None:
        if cur.data not in flag:
            flag.add(cur.data)
            pre = cur
            cur = cur.next
        else:
            pre.next = cur.next
            cur = cur.next
    print_link(head)


def con_link(n):
    nums = list(map(int, n.split(' ')))
    head = Node()
    cur = head
    for num in nums:
        node = Node(num)
        cur.next = node
        cur = node
    print_link(head)
    delete_rep(head)


if __name__ == '__main__':
    n = input("请输入链表串:")
    con_link(n)

有序链表移除重复项

# -*-coding:utf-8-*-
class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


def print_link(head):
    cur = head.next
    while cur.next != None:
        print(cur.data, end=' ')
        cur = cur.next
    print(cur.data)


def delete_rep(head):
    pre = head
    cur = head.next
    while pre.next != None:
        if pre.data == cur.data:
            pre.next = cur.next
        else:
            pre = cur
        cur = cur.next
    print_link(head)

def con_link(n):
    nums = list(map(int, n.split(' ')))
    head = Node()
    cur = head
    for num in nums:
        node = Node(num)
        cur.next = node
        cur = node
    print_link(head)
    delete_rep(head)


if __name__ == '__main__':
    n = input(">>>:")
    con_link(n)
原文地址:https://www.cnblogs.com/miao-study/p/11458421.html