單向鍊錶,實現了增刪改查以及鍊錶反轉,
class node:
def __init__(self, val):
self.val = val
self.nextp = none
class linkedlist:
def __init__(self):
self.length = 0
self.head = none
self.tail = none
def is_empty(self):
return self.length == 0
def clear(self):
self.head = self.tail = none
self.length = 0
def locate(self, posi):
now = self.head
for i in range(posi - 1):
now = now.nextp
return now
if not self.is_empty(): # 如果已經有元素
now = self.locate(self.length)
val = node(val)
now.nextp = val
self.length += 1
self.tail = val
else: # 如果鍊錶為空
self.tail = self.head = node(val)
self.length = 1
def prepend(self, val):
val = node(val)
head = self.head
self.length += 1
self.head, val.nextp = val, self.head
def search(self, value): # 第乙個位置為0
now = self.head
posi = 0
while now.nextp != none:
if now.val != value:
posi += 1
now = now.nextp
else:
return posi
if now.val != value:
print('no such element')
return none
def insert(self, posi, value):
if posi > self.length: # 插入超界
print('index beyond maxium')
return none
if posi == 0 and not self.is_empty(): # 如果要插入的位置為零且非空
self.prepend(value)
return none
if posi <= self.length:
ele = node(value)
now = self.locate(posi)
now.nextp, ele.nextp = ele, now.nextp
if posi == self.length:
self.tail = ele
return none
def show_all(self):
if not self.is_empty():
now = self.head
while now.nextp != none:
print(now.val)
now = now.nextp
print(now.val)
else:
print('empty list')
def reverse(self):
if self.is_empty():
print('empty')
return none
if self.length == 1:
print('done')
return none
else:
a, b = self.head, self.head.nextp
for i in range(self.length - 2):
c = b.nextp
b.nextp, a, b = a, b, c
b.nextp = a
self.head, self.tail = self.tail, self.head
self.tail.nextp = none
def del_posi(self, posi):
if not self.is_empty():
if posi > self.length:
print('beyond index')
return none
if posi == 0:
if self.length == 1:
self.clear()
else:
self.head = self.head.nextp
self.length -= 1
return none
if posi <= self.length:
now = self.locate(posi - 1)
print(now.val)
now.nextp = now.nextp.nextp
self.length -= 1
def __str__(self):
return "quantity:{} head:{} tail:{}".format(self.length, self.head.val, self.tail.val)
def __iter__(self):
now = self.head
yield now.val
for i in range(self.length - 1):
now = now.nextp
yield now.val
l = linkedlist()
for i in range(10):
print(l)
l2 = [i for i in l]
print(l2)
l.insert(3, 'a')
l.del_posi(6)
print('********************=')
l.show_all()
l.search('a')
l.reverse()
l.is_empty()
l.prepend('abc')
l.clear()
單向鍊錶的增刪改查
define crt secure no warnings include include includetypedef struct data typedef struct node cltype 追加結點 cltype claddend cltype head,data nodedata els...
單向迴圈鍊錶的增刪改查的實現
package datastructures.list public class mysinglecircularnode 在指定的結點後面加入新結點 param element 指定結點元素 param node 新結點 public void insert int element,mysingl...
C語言 單向鍊錶的增刪改查
什麼是鍊錶?1.和陣列一樣,鍊錶也是一種線性表 2.從記憶體結構來看 鍊錶的記憶體結構是不連續的記憶體空間,是將一組零散的記憶體塊串聯起來,從而進行資料儲存的資料結構。3.鍊錶中的每乙個記憶體塊被稱為節點node。節點除了儲存資料之外,還要記錄鏈上 下乙個節點的位址,即後繼指標next。1.查詢單向...