利用python 实现了单向链表
实现的方法有
1 is_empty() 判断链表是否为空
2 length()返回链表的长度
3 iteration() 遍历链表 并把链表的内容放在一个列表返回
4 append(item) 从链表尾部追加新节点
5 leftappend(item) 从链表头部添加新节点
6 insert(index,item) 在某一位置插入一个新节点
7 exist(item) 判断元素是否在链表中
8 remove(item) 删除链表中内容为item的节点
具体代码如下
class SingleNode(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 == None
def length(self):
"""获取链表的长度"""
# 开始游标指向头
cursor = self.__head
# 统计长度
count = 0
# 当cursor不为None时,统计加1,游标下移
while cursor != None:
count += 1
cursor = cursor.next
return count
def iteration(self):
"""遍历链表"""
res_list = []
# 初始游标指向头
cursor = self.__head
#当cursor 不为None时,取出节点的item,append进res_list,然后游标下移
while cursor != None:
res_list.append(cursor.item)
cursor = cursor.next
return res_list
def leftappend(self,item):
"""从头部添加一个节点"""
# 新建一个节点
new_node = SingleNode(item)
# 把新节点的next指向self.__head
new_node.next = self.__head
# 把self.__head 指向新节点
self.__head = new_node
def append(self,item):
"""从后面追加"""
# 新建一个节点
new_node = SingleNode(item)
# 判断链表是否为空
if self.is_empty():
self.__head = new_node
else:
# 初始化游标
cursor = self.__head
while cursor.next != None:
cursor = cursor.next
cursor.next = new_node
def insert(self,index,item):
"""指定位置添加"""
# 先判断指定位置
# 如果index = 0:
if index <= 0:
self.leftappend(item)
elif index > self.length() - 1:
self.append(item)
else:
# 新建一个节点
new_node = SingleNode(item)
count = 0
# 插入位置的前一个节点
previous = self.__head
while count < index - 1:
count += 1
previous = previous.next
# 将新建接点的next指向previous的next
new_node.next = previous.next
# 将previous的next指向new_node
previous.next = new_node
def exist(self,item):
"""查看节点是否存在"""
cursor = self.__head
while cursor != None:
if cursor.item == item:
return True
cursor = cursor.next
return False
def remove(self, item):
"""删除节点"""
# 判断是否存在链表中
if not self.exist(item):
return
cursor = self.__head
previous = None
while cursor != None:
if cursor.item == item:
# 第一个节点的就是要删除的节点
if not previous:
self.__head = cursor.next
else:
# 删除节点
previous.next = cursor.next
break
else:
# 前一个节点下下移
previous = cursor
# 游标向下移
cursor = cursor.next
if __name__ == '__main__':
linklist = SingleLinkList()
linklist.leftappend(1)
linklist.leftappend(2)
linklist.append(3)
linklist.append(5)
linklist.insert(5,4)
print(linklist.iteration())
print(linklist.exist(3))
linklist.remove(3)
linklist.remove(199)
print(linklist.exist(3))
print(linklist.iteration())
print(linklist.is_empty())
print(linklist.length())
print(linklist.exist(1))
#结果如下
#[2, 1, 3, 5, 4]
#True
#False
#[2, 1, 5, 4]
#False
#4
#True