1 Star 0 Fork 0

zhao-shu-bo/czsf

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
链表 3.58 KB
Copy Edit Raw Blame History
zhao-shu-bo authored 2021-11-09 20:57 +08:00 . add 链表.
#单链表插入和删除一个节点的伪代码算法
#单链表插入一个节点
Write 'a1 a2 a3 ... ai-1 ai+1 ... an-1 an'
Read SingleLinkList
Set ai-1 as node P
Set ai+1 as node Q(#P——>next == Q)
Set ai as node t
Set P——>next to t
Set t——>next to Q
#单链表删除一个节点
Write 'a1 a2 a3 ... ai-1 ai+1 ... an-1 an'
Read SingleLinkList
Set ai-1 as node P
Set ai as node t
Set ai+1 as node Q(#P——>next == t, t——>next == Q)
Set P——>next = Q
#python中实现单链表插入和删除一个节点
#创建一个节点
class Node(object):
"""节点"""
def __init__(self, elem):
self.elem = elem
self.next = None # 初始设置下一节点为空
'''上面定义了一个节点的类'''
# 下面创建单链表,并实现其应有的功能
class SingleLinkList(object):
"""单链表"""
def __init__(self, node=None): # 使用一个默认参数,在传入头结点时则接收,在没有传入时,就默认头结点为空
self.head = node
def is_empty(self):
'''链表是否为空'''
return self.head == None
def length(self):
'''链表长度'''
# cur游标,用来移动遍历节点
cur = self.head
# count记录数量
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
'''遍历整个列表'''
cur = self.head
while cur != None:
print(cur.elem, end=' ')
cur = cur.next
print('\n')
def add(self, item):
'''链表头部添加元素'''
node = Node(item)
node.next = self.head
self.head = node
def append(self, item):
'''链表尾部添加元素'''
node = Node(item)
# 由于特殊情况当链表为空时没有next,所以在前面要做个判断
if self.is_empty():
self.head = node
else:
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self, pos, item):
'''指定位置添加元素'''
if pos <= 0:
# 如果pos位置在0或者以前,那么都当做头插法来做
self.add(item)
elif pos > self.length() - 1:
# 如果pos位置比原链表长,那么都当做尾插法来做
self.append(item)
else:
per = self.head
count = 0
while count < pos - 1:
count += 1
per = per.next
# 当循环退出后,per指向pos-1位置
node = Node(item)
node.next = per.next
per.next = node
def remove(self, item):
'''删除节点'''
cur = self.head
per = None
while cur != None:
if cur.elem == item:
# 先判断该节点是否是头结点
if cur == self.head:
self.head = cur.next
else:
per.next = cur.next
break
else:
per = cur
cur = cur.next
def search(self, item):
'''查找节点是否存在'''
cur = self.head
while not cur:
if cur.elem == item:
return True
else:
cur = cur.next
return False
l = SingleLinkList()
print(l.length())
l.append(1)
l.add(2)
l.insert(0, 3)
l.insert(1, 4)
l.travel()
l.remove(4)
l.travel()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhao-shu-bo/czsf.git
git@gitee.com:zhao-shu-bo/czsf.git
zhao-shu-bo
czsf
czsf
master

Search