python实现链表


# @File: linklist


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


# 链表的实现:带头节点的链表 不带头节点的链表

# 带头节点的链表

# 头插法
def create_link_list_head(li):
    head = Node(None)
    for num in li:
        p = Node(num)
        p.next = head.next
        head.next = p
    return head


# 尾插法
def create_link_list_tail(li):
    head = Node(None)
    tail = head
    for num in li:
        p = Node(num)
        tail.next = p
        tail = p
    return head


# 打印输出
def traverse_link_list(head):
    p = head.next
    while p:
        print(p.data)
        p = p.next


# head = create_link_list_head([1, 2, 3, 4, 5])
# head = create_link_list_tail([1, 2, 3, 4, 5])
# traverse_link_list(head)


# 不带头节点的链表

# 头插法
def create_link_list_head2(li):
    head = None
    for num in li:
        p = Node(num)
        p.next = head
        head = p
    return head


# 尾插法
def create_link_list_tail2(li):
    head = None
    tail = head
    for num in li:
        p = Node(num)
        if tail:
            tail.next = p
            tail = p
        else:
            tail = p
            head = p
    return head


# 打印
def traverse_link_list2(head):
    p = head
    while p:
        print(p.data)
        p = p.next


head = create_link_list_head2([1, 2, 3, 4, 5])
head = create_link_list_tail2([1, 2, 3, 4, 5])
traverse_link_list2(head)
# s = iter([1, 2, 3])
# print(s.__next__())

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


# 头插法 (带头节点的方式)
def create(li):
    head = Node(None)
    for num in li:
        p = Node(num)
        p.next = head.next
        head.next = p
    return head


# 计算链表的长度
def size(head):
    count = 0
    p = head.next
    while p:
        count += 1
        p = p.next
    return count


# 查询链表中元素
def search(head, item):
    current = head
    found = False
    while current and not found:
        if current.data == item:
            found = True
        else:
            current = current.next
    return found


# 删除链表中元素
def remove(head, item):
    current = head
    previous = None
    found = False
    while not found:
        if current.data == item:
            found = True
        else:
            previous = current
            current = current.next
    previous.next = current.next


# 打印
def print_list(head):
    p = head.next
    while p:
        print(p.data)
        p = p.next


head = create([1, 2, 3, 4, 5])
print_list(head)
# print_list(head)
# print(size(head))
# print(search(head, 11))
print("remove", remove(head, 1))
print_list(head)
原文地址:https://www.cnblogs.com/xiao-xue-di/p/10168273.html