golang版本:
https://blog.csdn.net/lucky404/article/details/90716410
"""
使用python实现单链表
add 操作:在链表首部添加
append 操作:在链表尾部添加,从头部找到最后一个元素,把最后一个元素指针指向需要添加的元素
insert 操作:在指定位置添加,往中间插入元素,需要调整插入该位置的元素之前的指针,还有该元素的指针需要指向下一位
delete 操作:删除指定的元素,删除任意位置的元素,需要调整指针
"""
class LinkList(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkNode(object):
def __init__(self):
self.head = None
def isEmpty(self):
"""
链表是否为空
:return:
"""
if self.head is None:
return True
else:
return False
def length(self):
"""
获取长度
:return:
"""
node = self.head
count = 0
while node:
count += 1
node = node.next
return count
def add(self, value):
"""
在首部添加元素
:param value:
:return:
"""
head = self.head
newNode = LinkList(value)
if head is None:
self.head = newNode
else:
newNode.next = self.head
self.head = newNode
def append(self, value):
"""
在尾部添加元素
:param value:
:return:
"""
newNode = LinkList(value)
head = self.head
if head is None:
self.head = newNode
else:
while head.next:
head = head.next
head.next = newNode
def delete(self, value):
"""
删除指定元素
:param value:
:return:
"""
head = self.head
if head is None:
return
if value == head.data:
self.head = head.next
else:
while head.next:
if head.next.data == value:
head.next = head.next.next
else:
head = head.next
def insert(self, index, value):
"""
在指定位置插入数据
:param index:
:param value:
:return:
"""
if index < 0:
self.add(value)
elif index > self.length():
self.append(value)
else:
head = self.head
count = 0
while count < (index - 1):
count += 1
head = head.next
newNode = LinkList(value)
newNode.next = head.next
head.next = newNode
def range(self):
"""
循环链表
:return:
"""
head = self.head
while head:
print("当前元素是: %s" % head.data)
head = head.next
if __name__ == "__main__":
link = LinkNode()
link.append(0)
link.append(1)
link.add(2)
link.add(3)
link.insert(1, 5)
link.append(4)
link.range()
print("============ 链表是否为空: %s ==============" % link.isEmpty())
print("============== 链表长度: %s ================" % link.length())
link.delete(4)
link.range()