#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: json_steve
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):
"""链表的长度"""
cur = self.__head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
cur = self.__head
while cur is not None:
print(cur.item, end=' ')
cur = cur.next
print()
def add(self, item):
"""链表头部添加元素"""
node = Node(item)
node.next = self.__head
self.__head = node
def append(self, item):
"""链表尾部添加元素"""
if self.is_empty():
self.add(item)
return
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:
cur = self.__head
index = 0
while index < (pos - 1):
index += 1
cur = cur.next
# 循环结束cur指向pos前面的一个节点
node = Node(item)
node.next = cur.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__':
sll = SingleLinkList()
print(sll.is_empty())
print(sll.length())
sll.add(5)
sll.add(3)
sll.add(2)
print(sll.is_empty())
sll.travel()
print(sll.length())
sll.append(1)
sll.travel()
sll.insert(2, 4)
sll.travel()
sll.insert(-10, 6)
sll.travel()
sll.insert(10, 7)
sll.travel()
sll.remove(6)
sll.travel()
sll.remove(3)
sll.travel()
sll.remove(7)
sll.travel()
print(sll.search(2))
print(sll.search(1))
print(sll.search(3))
python实现单向链表
最新推荐文章于 2022-09-07 10:05:24 发布