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