class Node(object):
"""节点"""
def __init__(self, item):
# 用于保存数据
self.item = item
# 用于保存下一个节点地址
self.next = None
class SingleLinkList(object):
"""单链表"""
def __init__(self):
# 单链表初始化为空
self.__head = None
def is_empty(self):
return self.__head is None
def length(self):
count = 0 # 记录所有节点的数量
cur = self.__head
while cur is not None:
count += 1
cur = cur.next
return count
def add(self, item):
"""首位添加"""
node = Node(item)
node.next = self.__head
self.__head = node
def travel(self):
"""遍历单链表"""
cur = self.__head
while cur is not None:
print(cur.item)
cur = cur.next
def append(self, item):
"""链表尾部添加元素"""
if self.is_empty():
self.add(item)
else:
cur = self.__head
while cur.next is not None:
cur = cur.next
node = Node(item)
cur.next = node
def insert(self, pos, item):
"""指定位置添加元素"""
if pos <= 0:
self.add(item)
elif pos > (self.length() - 1):
self.append(item)
else:
node = Node(item)
cur = self.__head
index = 0
while index < (pos - 1):
cur = cur.next
index += 1
# 循环结束,当前cur就是要插入元素的前节点
node.next = cur.next
# 前节点的next指向插入元素
cur.next = node
def remove(self, item):
"""删除节点"""
cur = self.__head
pre = None
while cur is not None:
if cur.item == item:
# 要删除的是首节点
if pre is None:
self.__head = cur.next
else:
pre.next = cur.next
pre = cur
cur = cur.next
def search(self,item):
"""查找节点是否存在"""
cur=self.__head
while cur is not None:
if cur.item==item:
return True
cur=cur.next
return False
if __name__ == '__main__':
slist = SingleLinkList()
slist.add(1)
slist.append(4)
slist.insert(0, 2)
slist.travel()
print(slist.search(3))