線性表在python中有元組、列表、集合以及字典,非線性表目前介紹鏈表。
1.線性表對比
名稱 | 存儲類型 | 是否可變 | 是否有序 | 存儲是否可重復 |
列表 | 1.使用中括號括起來;如 list=[1,2,3,4] 2.可以存儲任何類型; 3.可以存儲不同類型的數據(不建議); | 可以增、刪、改、查; | 是 | 是 |
元組 | 1.使用小括號括起來;如 tuple = (1,2,3,4) 2.可以存儲任何類型; 3.可以存儲不同類型的數據(不建議) | 可以查; | 是 | 是 |
集合 | 1.使用小括號括起來,參數一般是一個list;如 set = set([1,2,3,4]) 2.一般傳入的是一個列表; | 可以增、刪、改、查; | 無 | 否 |
字典 |
1.使用大括號括起來,鍵值對的方式;如 dict ={"a":1,"b":2} 2.只能使用不可變類型作為鍵,值得類型任意; |
可以增、刪、改、查; |
無 |
否 |
2.鏈表
通俗來講,鏈表鏈表就是像一條鏈子一樣把數據穿起來形成一張表。鏈表存儲方式是不連續存儲,上一個數據通過地址來尋找下一個數據的存儲位置。所以鏈表的每一個存儲但是是數據+下一個數據存儲的地址,稱為節點;如圖
3.鏈表和列表的區別
列表 | 鏈表 | |
讀取 | O(1) | O(n) |
插入 | O(n) | O(1) |
刪除 | O(1) | O(n) |
4.鏈表的操作
仿照列表,鏈表會有增、刪、改、查,其中增又有頭插、尾查、任意位置插入。查又有遍歷和給定條件查詢。
代碼:
"""節點的聲明,節點是鏈表的基本組成部分"""
class Node(object):
def __init__(self, item):
self.item = item # 存儲數據的部分
self.next = None # 存儲地址的部分
"""單鏈表的操作"""
class SigleLink(object):
def __init__(self):
self.__head = None # 鏈表給定一個頭節點
def add(self, item):
"""在開頭插入數據"""
node = Node(item)
node.next = self.__head
self.__head = node
def is_empty(self):
"""判斷是否為空"""
return self.__head is None
def length(self):
"""計算長度"""
count = 0
cur = self.__head
while cur != None:
count += 1
cur = cur.next
return count
def append(self, item):
"""尾插法"""
node = Node(item)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next!=None:
cur = cur.next
print self.__head
cur.next = node
def insert(self, pos, item):
"""指定的位置插入"""
if pos <=0:
self.add(item)
elif pos > self.length()-1:
self.append(item)
else:
node = Node(item)
pre = self.__head
count = 0
while count < pos-1:
count+=1
pre = pre.next
node.next = pre.next
pre.next = node
def remove(self, item):
"""刪除第一個發現的元素"""
cur = self.__head
pre = None
while cur != None:
if cur.item == item:
if not pre:
self.__head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def travel(self):
"""遍歷"""
cur = self.__head
while cur!=None:
print cur.item,
cur = cur.next
def search(self, item):
"""查找"""
cur = self.__head
while cur!=None:
if cur.item ==item:
return True
else:
cur = cur.next
return False