python 鏈表
阿新 • • 發佈:2017-06-22
lin als his cli emp 索引 刪除 表鏈 pty
在C/C++中,通常采用“指針+結構體”來實現鏈表;而在Python中,則可以采用“引用+類”來實現鏈表。
節點類:
class Node: def __init__(self, data): self.data = data self.next = None
鏈表類:
class Linkedlist: def __init__(self): self.head = None self.tail = None
link_list = LinkedList()
def is_empty(self):return self.head is None
def append(self, data): node = Node(data) if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail =node
def iter(self): if not iter.head: return cur = self.head yield cur.datawhile cur.next: cur = cur.next yield cur.data #先判斷是不是空鏈表,yield head.data 再用while循環遍歷
鏈表的頭結點head 和 尾節點tail 都屬於node
def insert(self, idx, value): cur = self.head cur_idx = 0 if cur is None: raise Exception(‘That list is and empty list!‘) while cur_idx < idx-1: cur= cur.next if cur is None: raise Exception(‘List length less than index!‘) cur_idx += 1 node = Node(value) node.next = cur.next cur.next = node if node.next is None: self.tail = node
def remove(self, idx): cur = self.head cur_idx = 0 #空指針 if self.head = None: raise Exception(‘This is an empty list‘) while cur_idx < idx-1: cur = cur.next #給出的索引大於鏈表的長度 if cur is None: raise Exception(‘list length less than index‘) cur_idx +=1 if idx == 0: #當刪除第一個節點時 self.head = cur.next cur = cur.next return if self.head is self.tail: #當只有一個節點時 self.head = None self.tail = None return cur.next = cur.next.next if cur.next is None: #當刪除最後一個節點時 self.tail = cur
def size(self): i = 0 cur = self.head if current is None: return ‘The list is an empty list‘ while cur.next is not None: i +=1 cur = cur.next return i
def search(self, item): current = self.head found = False while current is not None and not found: if current.data == item: found = True else: current = current.next return found
insert:先將要插入的節點的next指向之後鏈表的head,然後將之前鏈表的next指向 將要插入的節點。
SinCycLinkedlist類代表單向循環鏈表,Node類代表鏈表中的一個節點:
python 鏈表