class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
# 通过单链表构建一个list的结构: 添加 删除 插入 查找 获取长度 判断是否为空...
# list1 = [] list1.append(5) [5,] slist = SingleList() slist.append(5)
class SingleList:
def __init__(self, node=None):
self._head = node
def isEmpty(self):
return self._head == None
def append(self, item):
# 尾部添加
node = Node(item)
if self.isEmpty():
self._head = node
else:
cur = self._head
while cur.next != None:
cur = cur.next
cur.next = node
# 求长度
def len(self):
cur = self._head
count = 0
while cur != None:
count += 1
cur = cur.next
return count
# 遍历
def print_all(self):
cur = self._head
while cur != None:
print(cur)
cur = cur.next
def pop(self, index):
if index < 0 or index >= self.len():
raise IndexError('index Error')
if index == 0:
self._head = self._head.next
else:
cur = self._head
# 找到当前下标的前一个元素
while index - 1:
cur = cur.next
index -= 1
# 修改的next的指向位置
cur.next = cur.next.next
def insert(self, index, item):
if index < 0 or index >= self.len():
raise IndexError('index Error')
if isinstance(item, Node):
raise TypeError('不能是Node类型')
else:
node = Node(item)
if index == 0:
node.next = self._head
self._head = node
else:
cur = self._head
while index - 1:
cur = cur.next
index -= 1
node.next = cur.next
cur.next = node
def update(self, index, new_item):
pass
def remove(self, item):
if self.isEmpty():
raise ValueError('没有找到该元素')
else:
cur = self._head
if cur.data ==item:
#删除的是头的节点
if cur.next ==None:
#只有头节点
self._head = None
else:
#除了头部节点,还有其他的节点
cur.next.prev = None
self._head = cur.next
else:
while cur !=None:
if cur.data == item:
cur.prev.next = cur.next
cur.next.prev = cur.prev
break
cur = cur.next
if __name__ == '__main__':
slist = SingleList()
print(slist.isEmpty()) # True
print(slist.len())
slist.append(5)
print(slist.isEmpty()) # False
print(slist.len()) # 1
slist.append(8)
slist.append(6)
slist.append(3)
slist.append(1)
print(slist.isEmpty()) # True
print(slist.len())
print('---------------------')
slist.print_all()
print('----------pop-------------')
slist.pop(2)
slist.print_all()
print('--------insert-------')
slist.insert(1, 19)
slist.remove(3)
slist.print_all()
单链表
于 2019-08-22 19:36:33 首次发布