# 链表的结构 node1 -> node2 -> node3 -> node4 ->None
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __str__(self):
return str(self.value)
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
# 链表的串联
node1.next = node2
node2.next = node3
# 遍历链表
def print_node(node):
while node: # 表示node有内容,不是None
print(node.value)
# print(node.next)
node = node.next
# 递归便利列表
def printBackward(node):
if node == None:
return
head = node
tail = node.next
printBackward(tail)
print(head)
class LinkedList(object):
def __init__(self, head=Node):
self.head = head
def __len__(self):
‘反应列表长度‘
curr = self.head
counter = 0
while curr is not None:
counter += 1
curr = curr.next
return counter
def insertFront(self, data):
‘列表首部插入数据‘
if data is None:
return None
node = Node(data, self.head)
self.head = node
return node
def append(self, data):
‘链表尾部追加数据‘
if data is None:
return None
node = Node(data)
if self.head is None:
self.head = node
return node
curr_node = self.head
while curr_node.next is not None:
curr_node = curr_node.next
curr_node.next = node
return node
def find(self,data):
‘查找链表数据‘
if data is None:
return None
curr_node = self.head
while curr_node is not None:
if curr_node.value == data:
return curr_node
curr_node = curr_node.next
return None
def deleteData(self,data):
‘删除链表数据‘
if data is None:
return None
if self.head is None:
return None
if self.head == data:
self.head = self.head.next
return
curr_node = self.head
while curr_node.next is not None:
if curr_node.next.value == data:
curr_node.next = curr_node.next.next
return
curr_node = curr_node.next
原文:https://www.cnblogs.com/testerWangzhao/p/13844095.html