创建一个单链表:
class LinkNode: #设置属性
def __init__(self,data = None):
self.data = data
self.next = None
class LinkList: #设置头结点
def __init__(self):
self.head = LinkNode()
self.head.next = None
def CreateListR(self,a): #尾插法
t = self.head
for i in range(len(a)):
s = LinkNode(a[i]) #建立节点
t.next = s
t = s
t.next = None #让尾结点变为空值
a = LinkList()
a.CreateListR([3,2,6,7,1]) #创建另一个单链表
b = LinkList() #
b.CreateListR([3,2,1]) #创建一个单链表
创建一个双链表:
class DlinkNode:
def __init__(self,data = None):
self.data = data
self.next = None
self.prior = None
class Dlinklist:
def __init__(self):
self.dhead = DlinkNode()
self.dhead.next = None
self.dhead.prior = None
def CreatelistR(self,a): #尾插法
t = self.dhead
for i in range(len(a)):
s = DlinkNode(a[i])
t.next = s
s.prior = t
t = s
t.next = None
def getsize(self): #返回链表长度
p = self.dhead
cnt = 0
while p.next != None:
cnt+=1
p = p.next
return cnt
def geti(self,i): #返回序号为i的元素
p = self.dhead
j = -1
while j<i and p.next!=None:
j+=1
p = p.next
return p
a = Dlinklist()
a.CreatelistR([1,2,3,4,5,6,9])
两个单链表递归求和:
def Sum(m): #两个单链表求和
if m==None: #如果两个单链表尾节点的下一节点为空就返回0
return 0
else:
return m.data+Sum(m.next)
p = Sum(a.head.next)
m = Sum(b.head.next)
print(p+m)
双链表用递归从中间求和:
def Sum(p,x): #双链表用递归从中间求和
if p==None or x ==None:
return 0
else:
return p.data+Sum(p.next,x.prior)+x.data #p指针向后移动,x指针向前移动
size = a.getsize() #获取整体长度
if size%2==0:
minddle = size//2 #找到中间序号
it = a.geti(minddle) #找到中间节点
o = Sum(it,it.prior) #注意传后面的it是要向前移一个
print(o)
if size%2==1:
minddle = size//2
it = a.geti(minddle)
o = Sum(it.next,it.prior)+it.data
print(o)
用递归求链表的最小值:
def Min(p): #用递归求链表的最小值
if p.next==None: #只有一个就直接返回
return p.data
min = Min(p.next) #设为初始最小值
if min<p.data:
return min #p向下移动
else:
return p.data #返回最小值
a = Min(a.head.next)
print(a)