# coding: utf-8
# 链表节点
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
# 单向不循环链表
class LinkList(object):
def __init__(self):
self._head = None
def is_empty(self):
# 判断链表是否为空
return self._head is None
def length(self):
# 链表长度
num = 0
cur = self._head
while cur is not None:
num += 1
cur = cur.next
return num
def travel(self):
# 遍历链表
cur = self._head
while cur is not None:
print(cur.item, end=' ')
cur = cur.next
print('length:', self.length())
def add(self, item):
# 头插
node = Node(item)
node.next = self._head
self._head = node
def append(self, item):
# 尾插
node = Node(item)
if self.is_empty():
self._head = node
else:
cur = self._head
while cur.next is not None:
cur = cur.next
cur.next = node
def insert(self, pos, item):
# 在pos位置插
if pos <= 0:
self.add(item)
elif pos >= self.length():
self.append(item)
else:
node = Node(item)
cur = self._head
pos_cur = 0
while pos_cur + 1 != pos:
cur = cur.next
pos_cur += 1
node.next = cur.next
cur.next = node
def remove(self, item):
# 链表中找到元素item并从链表中移除
if self.is_empty():
return 'List is empty.'
cur = self._head
if cur.item == item:
self._head = cur.next
else:
while cur.next is not None and cur.next.item != item:
cur = cur.next
if cur.next.item == item:
cur.next = cur.next.next
def search(self, item):
# 查找元素item是否在链表中
cur = self._head
while cur is not None:
if cur.item == item:
return True
else:
cur = cur.next
return False
if __name__ == '__main__':
a = LinkList()
a.travel()
a.append(1)
a.travel()
a.append(2)
a.travel()
a.add(3)
a.travel()
a.append(100)
a.travel()
a.insert(1, 600)
a.travel()
a.insert(0, 700)
a.travel()
a.insert(6, 1314)
a.travel()
a.insert(6, 520)
a.travel()
a.remove(1)
a.travel()
a.remove(1314)
a.travel()
a.remove(700)
a.travel()
print(a.search(100))
print(a.search(1314))
单向不循环链表(创建、遍历、增、删、查找、判空)
最新推荐文章于 2022-07-30 00:05:44 发布