码迷,mamicode.com
首页 > 编程语言 > 详细

Python实现无序列表:链表

时间:2018-01-26 14:12:40      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:快速   数组下标   实现   ==   end   else   head   []   while   

链表有什么用
数组: 优点: 通过索引(数组下标)可以很快地访问数组元素;缺点: 插入/删除元素需要对数组进行调整, 效率低;
链表:优点:插入/删除速度很快,而且不用对整个链表进行调整;缺点:只能进行顺序访问,不能随机访问(像数组一样用下标);
所以,链表在一些需要快速插入/删除,而不太关心或者不需要随机访问的情况下使用
首先创建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实现无序列表:链表

标签:快速   数组下标   实现   ==   end   else   head   []   while   

原文地址:https://www.cnblogs.com/wangxiayun/p/8358991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!