Python实现无序列表:链表

Posted 薛定谔的猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python实现无序列表:链表相关的知识,希望对你有一定的参考价值。

链表有什么用
数组: 优点: 通过索引(数组下标)可以很快地访问数组元素;缺点: 插入/删除元素需要对数组进行调整, 效率低;
链表:优点:插入/删除速度很快,而且不用对整个链表进行调整;缺点:只能进行顺序访问,不能随机访问(像数组一样用下标);
所以,链表在一些需要快速插入/删除,而不太关心或者不需要随机访问的情况下使用
首先创建Node类
class Node:
	def __init__(self,initdata):
		self.data = initdata
		self.next = None
	def getData(self):
		return self.data
	def getNext(self):
		return self.next
	def setData(self,newdata):
		self.data = newdata
	def setNext(self,newnext):
		self.next = newnext  
创建操作链表的类
class UnorderedList:
	def __init__(self):
		self.head = None
	def isEmpty(self):
		self.head == None
	def add(self,item):
		temp = Node(item)
		temp.setNext(self.head)
		self.head = temp
	def size(self):
		current = self.head
		count = 0
		while current != None:
			count = count + 1
			current = current.getNext()
		return count
	def search(self,item):
		current = self.head
		found = False
		while current != None and not found:
			if current.getData() == item:
				found = True
			else:
				current = current.getNext()
		return found
	def getvalue(self):
		current = self.head
		currarr = []
		while current != None:
				currarr.append(current.getData())
				current = current.getNext()
		return currarr
	def remove(self,item):
		current = self.head
		previous = None
		found = False
		while not found:
			if current.getData() == item:
				found = True
			else:
				previous = current
				current = current.getNext()
		if previous == None:
			self.head = current.getNext()
		else:
			previous.setNext(current.getNext())

  

 






以上是关于Python实现无序列表:链表的主要内容,如果未能解决你的问题,请参考以下文章

Python实现单向有序链表(Singly linked list)

Python链表操作(实现)

Python数据结构学习笔记——链表:无序链表和有序链表

Python面试常考点之深入浅出链表操作

python 实现无序列表

简单的描述框架