有序列表 无序列表
Posted WANGLC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了有序列表 无序列表相关的知识,希望对你有一定的参考价值。
节点类
1 # python 2 # -*- coding: utf-8 -*- 3 """ 4 __title__ = ‘‘ 5 __author__ = ‘wlc‘ 6 __mtime__ = ‘2017/10/13‘ 7 """ 8 class Node: 9 def __init__(self, initData): 10 self.data = initData 11 self.next = None 12 #getData 13 def getData(self): 14 return self.data 15 #getNext 16 def getNext(self): 17 return self.next 18 #setData 19 def setData(self, data): 20 self.data = data 21 #setNext 22 def setNext(self, nextNode): 23 self.next = nextNode
无序列表
1 # python 2 # -*- coding: utf-8 -*- 3 """ 4 __title__ = ‘‘ 5 __author__ = ‘wlc‘ 6 __mtime__ = ‘2017/10/13‘ 7 """ 8 from dataStructure.dS import pythonLinkedListNode 9 10 class UnorderedList: 11 def __init__(self): 12 self.head = None 13 #isEmpty 14 def isEmpty(self): 15 return self.head == None 16 #add 17 def add(self, item): 18 lnode = pythonLinkedListNode.Node(item) 19 lnode.setNext(self.head) 20 self.head = lnode 21 #size 22 def size(self): 23 current = self.head 24 count = 0 25 while current != None: 26 count = count + 1 27 current = current.getNext() 28 return count 29 #serch 30 def search(self, item): 31 current = self.head 32 flag = False 33 while current != None and (not flag): 34 if current.getData() == item: 35 flag = True 36 else: 37 current.getNext() 38 return flag 39 #remove 40 def remove(self, item): 41 #链表删除元素由于链表不可以回退 因此需要设置两个指针一个当前位置一个上一个位置 42 previous = None 43 current = self.head 44 found = False 45 while not found: 46 if current.getData() == item: 47 found = True 48 else: 49 previous = current 50 current = current.getNext() 51 #precious如果没有变化就说明头结点的数据就会说要删除的元素 52 if previous == None: 53 self.head = current.getNext() 54 else: 55 previous.setNext(current.getNext())
有序列表
1 # python 2 # -*- coding: utf-8 -*- 3 """ 4 __title__ = ‘‘ 5 __author__ = ‘wlc‘ 6 __mtime__ = ‘2017/10/13‘ 7 """ 8 from dataStructure.dS import pythonLinkedListNode 9 10 11 class orderedList: 12 def __init__(self): 13 self.head = None 14 15 # isEmpty 16 def isEmpty(self): 17 return self.head == None 18 19 # size 20 def size(self): 21 current = self.head 22 count = 0 23 while current != None: 24 count = count + 1 25 current = current.getNext() 26 return count 27 #search 28 def search(self, item): 29 current = self.head 30 found = False 31 stop = False 32 while current != None and not found and not stop: 33 if current.getData() == item: 34 found = True 35 else: 36 if current.getData() > item: 37 stop = True 38 else: 39 current = current.getNext() 40 return found 41 #add 42 def add(self, item): 43 current = self.head 44 previous = None 45 stop = False 46 while current != None and not stop: 47 if current.getData() > item: 48 stop = True 49 else: 50 previous = current 51 current = current.getNext() 52 temp = pythonLinkedListNode.Node(item) 53 if previous == None: 54 temp.setNext(self.head) 55 self.head = temp 56 else: 57 temp.setNext(current) 58 previous.setNext(temp)
以上是关于有序列表 无序列表的主要内容,如果未能解决你的问题,请参考以下文章