- 基本定義
有序表是一種數據項依照其某科比性質(如整數大小、字母表先后)來決定在列表中的位置。越小的數據越靠近列表的頭,越靠前。
- 基本屬性
orderedList() |
創建一個有序表 |
add(item) | 加入一個數據項,並保持整體順序 |
remove(item) | 從有序表中移除一個數據項,有序表被修改 |
search(item) | 查找數據項,返回bool類型 |
isEmpty() | 是否空表 |
size() | 返回表中數據項的個數 |
index(item) | 返回數據項在表中的索引 |
pop() | 移除有序表最后一項 |
pop(pos) | 移除指定項 |
- 用鏈表實現有序表
這里需要注意的是有序表數據項的相對位置,取決於它們之間的“大小”比較。
1 from node import Node 2 class OrderedList(): 3 def __init__(self): 4 self.head = None #這里首先需要定義無須表的表頭head屬性,保存對第一個節點對的引用空表head為None. 5 def isEmpty(self): 6 return self.head == None 7 def add(self, item): 8 current = self.head 9 previous = None 10 stop = False 11 while current != None and not stop: 12 if current.getData() > item: 13 stop = True 14 else: 15 previous = current 16 current = current.getNext() 17 temp = Node(item) 18 if previous == None: 19 temp.setNext(self.head) 20 self.head = temp 21 else: 22 temp.setNext(current) 23 previous.setNext(temp) 24 25 def size(self): 26 current = self.head 27 count = 0 28 while current != None: 29 count += 1 30 current = current.getNext() 31 return count 32 33 def search(self,item): 34 current = self.head 35 found = False 36 while current != None and not found: 37 if current.getData() == item: 38 found = True 39 else: 40 if current.getData() > item: 41 stop = True 42 else: 43 current = current.getNext() 44 return found 45 46 s = OrderedList() 47 s.add(5) 48 s.add(6) 49 s.add(7) 50 s.add(6) 51 print(s.head.getData())
參考:https://www.bilibili.com/video/BV1QJ411w7bB?p=29