单链表的创建、增删改查等操作(Python实现)
class Node:
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkedList:
def __init__(self, length):
self.head = Node(length)
self.end = self.head
def length(self):
cur = self.head
count = 0
while cur.next :
count += 1
cur = cur.next
return count
def isempty(self):
return self.head.next == None
def add(self, elem):
node = Node(elem)
node.next = self.head.next
self.head.next = node
def append(self, elem):
node = Node(elem)
node.next = None
self.end.next = node
self.end = node
def insert(self, loc, elem):
cur = self.head
count = 0
while cur and count<loc-1:
cur = cur.next
count += 1
if not cur or count>loc-1:
print("插入失败")
return
node = Node(elem)
node.next = cur.next
cur.next = node
def remove(self, loc):
cur = self.head
count = 0
while cur.next and count<loc-1:
cur = cur.next
count += 1
if not cur.next or count>loc-1:
print("删除操作不合法")
return
cur.next = cur.next.next
def travel(self):
cur = self.head
while cur.next:
cur = cur.next
print(cur.elem)
if self.isempty():
print("该链表为空")
def getelem(self, loc):
cur = self.head.next
count = 1
while cur and count<loc:
cur = cur.next
count += 1
if not cur or count>loc :
print("不存在")
return
print(cur.elem)
def search(self, elem):
cur = self.head.next
while cur and cur.elem!=elem:
cur = cur.next
if cur and cur.elem==elem:
print(cur)
return
print("不存在")
pass
def main():
length = 0
sll = SingleLinkedList(length)
print(sll.isempty())
print(sll.length())
sll.append(1)
sll.append(2)
sll.append(3)
sll.append(4)
sll.append(5)
print(sll.length())
sll.travel()
main()