python单链表


class SingleNode(object):
	"""单链表的结点"""
	def __init__(self,data):
		self.data = data
		self.next = None

class SingleLinkList(object):
	"""单链表"""
	def __init__(self):
		self._head = None

	def is_empty(self):
		"""判断链表是否为空"""
		return self._head == None

	def length(self):
		"""判断链表的长度"""
		cur = self._head
		count = 0
		while cur != None:
			count +=1
			cur = cur.next
		return count

	def travel(self):
		"""遍历链表"""
		if self.is_empty():
			return
			
		cur = self._head
		while cur != None:
			print(cur.data)
			cur = cur.next

	def addhead(self,data):
		"""头部添加元素"""
		node = SingleNode(data)
		node.next = self._head
		self._head = node

	def append(self,data):
		"""尾部添加元素"""
		node = SingleNode(data)
		# 先判断链表是否为空,若是空链表,则将_head指向新节点
		if self.is_empty():
			self._head = node
		# 若不为空,则找到尾部,将尾节点的next指向新节点
		else:
			cur = self._head
			while cur.next !=None:
				cur = cur.next
			cur.next = node

	def insert(self,pos,data):
		"""插入指定位置"""
		
		# 若指定位置pos为第一个元素之前,则执行头部插入
		if pos<=0:
			self.addhead(data)

		# 若指定位置超过链表尾部,则执行尾部插入
		elif pos > (self.length() - 1):
			self.append(data)
		else:
			node = SingleNode(data)
			count = 0
			pre = self._head
			while count < (pos-1):
				count +=1
				pre = pre.next
			# 先将新节点node的next指向插入位置的节点
			node.next =pre.next
			# 将插入位置的前一个节点的next指向新节点
			pre.next = node

	def remove(self,data):
		"""删除节点"""
		cur = self._head
		pre = None
		while cur != None:
			if cur.data ==data:
				# 如果第一个就是删除的节点
				if not pre:
				# 将头指针指向头节点的后一个节点
					self._head = cur.next
				else:
					pre.next = cur.next
				break
			else:
				pre = cur
				cur = cur.next

	def search(self,data):
		"""链表查找节点是否存在,并返回True或者False"""
		cur = self._head
		while cur != None:
			if cur.data == data:
				return True
			cur = cur.next
		return False
if __name__ == '__main__':
	linkList = SingleLinkList()
	linkList.addhead(1)
	linkList.addhead(2)
	linkList.addhead(3)
	linkList.append(4)
	linkList.insert(2,5)
	print("length:%d " %linkList.length())
	linkList.travel()
	print(linkList.search(3))
	print(linkList.search(6))
	linkList.remove(5)
	linkList.travel()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值