Python數據結構之單鏈表
單鏈表有后繼結點,無前繼結點。
以下實現:
- 創建單鏈表
- 打印單鏈表
- 獲取單鏈表的長度
- 判斷單鏈表是否為空
- 在單鏈表后插入數據
- 獲取單鏈表指定位置的數據
- 獲取單鏈表指定元素的索引
- 刪除單鏈表指定位置的元素
- 更新單鏈表指定位置的元素
- 清空單鏈表
class Node(object):
"""定義類來描述指針"""
def __init__(self, data, p=None):
self.data = data
self.next = p
class LinkList(object):
"""單鏈表"""
def __init__(self):
self.head = None
# 初始化單鏈表
def create(self, data):
self.head = Node(data[0])
p = self.head
for i in data[1:]:
p.next = Node(i)
p = p.next
# 打印單鏈表
def print(self):
p = self.head
while p != None:
print(p.data)
p = p.next
# 獲取單鏈表的長度
def len(self):
p = self.head
length = 0
while p != None:
length += 1
p = p.next
return length
# 判斷單鏈表是否為空
def is_empty(self):
return self.len() == 0
# 在單鏈表后插入數據
def append(self, item):
if self.is_empty():
self.head = Node(item)
else:
p = self.head
while p.next != None:
p = p.next
p.next = Node(item)
# 獲取單鏈表指定位置的數據
def getItem(self, index):
if self.is_empty():
print("單鏈表為空")
return
if index >= self.len() or index < 0:
print("索引超過單鏈表長度")
return
p = self.head
count = 0
while count != index:
p = p.next
count += 1
return p.data
# 獲取單鏈表指定元素的索引
def find(self, item):
p = self.head
index = 0
while p != None:
if p.data == item:
return index
p = p.next
index += 1
print("單鏈表中不存在" + repr(item))
# 在單鏈表指定位置插入元素
def insert(self, index, item):
if self.is_empty():
print("單鏈表為空")
return
if index >= self.len() or index < 0:
print("索引超過單鏈表長度")
return
if index == 0:
self.head = Node(item, self.head)
else:
p = self.head
count = 0
while count < index-1:
p = p.next
count += 1
p.next = Node(item, p.next)
# 刪除單鏈表指定位置的元素
def delete(self, index):
if self.is_empty():
print("單鏈表為空")
return
if index >= self.len() or index < 0:
print("索引超過單鏈表長度")
return
if index == 0:
self.head = self.head.next
else:
p = self.head
count = 0
while count < index-1:
p = p.next
count += 1
p.next = p.next.next
# 更新單鏈表指定位置的元素
def update(self, index, data):
if self.is_empty():
print("單鏈表為空")
return
if index > self.len() or index < 0:
print("索引超過單鏈表長度")
return
p = self.head
count = -1
while count < index-1:
p = p.next
count += 1
p.data = data
# 清空單鏈表
def clear(self):
self.head = None
L = LinkList()
L.create([1, 2, 3])
print("打印單鏈表:")
L.print()
print("獲取單鏈表的長度:")
print(L.len())
print("單鏈表是否為空")
print(L.is_empty())
print("在單鏈表后插入數據")
L.append(4)
L.print()
index = 1
print("獲取第" + repr(index) + "個位置的數據")
print(L.getItem(index))
item = 3
print("獲取單鏈表中元素" + repr(item) + "的索引")
print(L.find(item))
index = 2
item = 10
print("在單鏈表的" + repr(index) + "位置插入數據" + repr(item))
L.insert(index, item)
L.print()
index = 2
print("刪除單鏈表"+repr(index)+"位置的元素")
L.delete(index)
L.print()
index = 2
item = 100
print("更新單鏈表"+repr(index)+"位置的元素為"+repr(item))
L.update(index, item)
L.print()
print("清空單鏈表")
L.clear()
L.print()
程序輸出結果:
打印單鏈表:
1
2
3
獲取單鏈表的長度:
3
單鏈表是否為空
False
在單鏈表后插入數據
1
2
3
4
獲取第1個位置的數據
2
獲取單鏈表中元素3的索引
2
在單鏈表的2位置插入數據10
1
2
10
3
4
刪除單鏈表2位置的元素
1
2
3
4
更新單鏈表2位置的元素為100
1
2
100
4
清空單鏈表