链表的插入和遍历
作者:
___大鱼___ | 来源:发表于
2019-08-22 15:42 被阅读0次
链表1.png
创建链表.png
# 链表
class Node:
def __init__(self, item):
self.item = item
self.next = None
def __str__(self):
return str(self.item)
# 头插法
def create_linklist_head(li):
head = Node(li[0])
for ele in li[1:]:
node = Node(ele)
node.next = head
head = node
return head
# 尾插法
def create_linklist_tail(li):
head = Node(li[0])
tail = head
for ele in li[1:]:
node = Node(ele)
tail.next = node
tail = node
return head
# 遍历链表
def print_linklist(head):
while head:
print(head.item)
head = head.next
if __name__ == '__main__':
node_head = create_linklist_tail([x for x in range(100)])
print_linklist(node_head) # 正序打印
node_head = create_linklist_head([x for x in range(100)])
print_linklist(node_head) # 倒叙打印
本文标题:链表的插入和遍历
本文链接:https://www.haomeiwen.com/subject/ohnnsctx.html
网友评论