标签:== __init__ search end bre 增删改查 第一个 break 创建
class Node():
def __init__(self, item):
self.item = item
self.next = None
class Link():
def __init__(self):
#构造一个空链表
#head存储只能是空或者第一个节点的地址
self._head = None
#头插
def add(self, item):
#创建一个新的结点
node = Node(item)
node.next = self._head
self._head = node
#遍历
def travel(self):
#_head在链表创建好后一定不可变
if self.isEmpty():
print("空链表")
return
cur = self._head
while cur:
print(cur.item)
cur = cur.next
def isEmpty(self):
return self._head == None
def size(self):
cur = self._head
count = 0
while cur:
count += 1
cur = cur.next
return count
def append(self, item):
node = Node(item)
if self._head == None:
self._head = node
return
cur = self._head
pre = None
while cur:
pre = cur
cur = cur.next
pre.next = node
def search(self,item):
flag = False
cur = self._head
while cur:
if cur.item == item:
flag = True
break
cur = cur.next
return flag
def insert(self,pos,item):
node = Node(item)
pre = None
cur = self._head
for i in range(pos):
pre = cur
cur = cur.next
pre.next = node
node.next = cur
def remove(self,item):
cur = self._head
pre = None
if cur.item == item:
self._head = cur.next
return
while cur:
pre = cur
cur = cur.next
if cur.item == item:
pre.next = cur.next
return
link1= Link()
link1.travel()
link1.append(1)
link1.append(3)
link1.append(4)
link1.travel()
print(link1.search(3))
print(link1.search(4))
link1.insert(1, 2)
link1.remove(4)
link1.travel()
# 空链表
# 1
# 3
# 4
# True
# True
# 1
# 2
# 3
标签:== __init__ search end bre 增删改查 第一个 break 创建
原文地址:https://www.cnblogs.com/gugu-da/p/13190936.html