Python实现单链表及其方法

Python实现单链表

class Node():
	def __init__(self,item):
		self.val = item
		self.next = None
		
		
class Singlelink():
	def __init__(self,node=None):
		self._head = node	
	def is_empty(self):
		return self._head == None
	def length(self):
		count = 0
		cur = self._head
		while cur != None:
			count += 1
			cur = cur.next
		return count
	# 遍历
	def travel(self):
		cur = self._head
		while cur != None:
			print(cur.val,end=' ')
			cur = cur.next
	# 尾插
	def append(self,item):
		if self.is_empty():
			self._head = Node(item)
		else:
			cur = self._head
			while cur.next != None:
				cur = cur.next
			cur.next = Node(item)	
	# 头插
	def add(self,item):
		node = Node(item)
		node.next = self._head
		self._head = node
	# 指定位置插入
	def insert(self,item,n):
		if n <= 0:
			self.add(item)
		elif n > self.length()-1:
			self.append(item)
		else:
			cur = self._head
			while n > 1:
				cur = cur.next
				n -= 1
			node = Node(item)
			node.next = cur.next
			cur.next = node
	# 查找
	def search(self,item):
		cur = self._head
		while cur != None:
			if cur.val == item:
				return True
			else:
				cur = cur.next
		return False
	# 删除
	def remove(self,item):
		cur = self._head
		pre = None
		while cur != None:
			if cur.val == item:
				if cur == self._head:
					self._head = cur.next
				else:
					pre.next = cur.next
			pre = cur
			cur = cur.next
				

link = Singlelink()
link.append(3)
link.add(5)
link.add(8)
link.insert(4,2)
link.remove(8)
print(link.search(1))
print(link.travel())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值