1. 新增元素到单向链表
#新增数据节点,并建立单向链表
import sys
class student:
def __init__(self):
=''
self.Math=0
self.Eng=0
self.no=''
self.next=None
head = student() #建立链表的头部
head.next=None
ptr = head
Msum = Esum = num = student_no = 0
select = 0
while select !=2:
print('(1)新增 (2)离开==>')
try:
select = int(input('请输入一个选项:'))
except ValueError:
print('输入错误')
print('请重新输入\n')
if select ==1:
new_data = student() #新增下一个元素
new_data.name=input('姓名:')
new_data.no=input('学号:')
new_data.Math=eval(input('数学成绩:'))
new_data.Eng=eval(input('英语成绩:'))
ptr.next=new_data #存取指针位置为新元素所在位置
new_data.next=None #下一个元素的net先设置为None
prt=ptr.next
num=num+1
ptr=head.next #设置存取指针从链表的头部开始
print()
while ptr != None:
print('姓名:%s\t 学号:%s\t 数学成绩:%d\t 英语成绩:%d\t'%(,ptr.no,ptr.Math,ptr.Eng) )
Msum=Msum+ptr.Math
Esum=Esum+ptr.Eng
student_no=student_no+1
ptr=ptr.next #将ptr移向下一个元素
if student_no != 0:
print('---------------------------------------------------------------------')
print('本链表中学生的数学平均成绩:%.2f 英语平均成绩:%.2f'%(Msum/student_no,Esum/student_no))C:\Users\Amber\AppData\Local\Programs\Python\Python36\python.exe C:/Python/Exercises/CH03_01.py
(1)新增 (2)离开==>
请输入一个选项:1
姓名:andy
学号:1
数学成绩:98
英语成绩:97
(1)新增 (2)离开==>
请输入一个选项:1
姓名:may
学号:2
数学成绩:95
英语成绩:96
(1)新增 (2)离开==>
请输入一个选项:2
姓名:may 学号:2 数学成绩:95 英语成绩:96
---------------------------------------------------------------------
本链表中学生的数学平均成绩:95.00 英语平均成绩:96.00
2. 基于Python单向链表实现尾部、任意位置添加,删除
# coding = utf-8
# 创建节点类
class Node(object):
def __init__(self, data):
# 定义指向域
self.next = None
# 定义数据域
self.data = data
# 创建链表类
class LinkDict(object):
def __init__(self):
self._head = Node(None)
self._length = 0
# 尾部添加元素
def append(self, data):
# 构造新节点
new_code = Node(data)
# 查找尾部节点并定义游标指向头节点,向尾部添加新节点
cur = self._head
# 循环遍历
while cur.next is not None:
# 移动游标
cur = cur.next
else:
# 向尾部添加新节点
cur.next = new_code
# 链表长度加1
self._length += 1
return self._length
# 循环遍历链表元素
def traval(self):
cur = self._head
while cur.next is not None:
# 打印后边节点
print(cur.next.data, "--->", end="")
# 游标后移
cur = cur.next
else:
print("None:now is terminal")
# 任意位置添加元素
def insert(self, pos, data):
# 判断插入点
if isinstance(pos, int):
if pos < 0:
link_dict.insert(0, data)
elif pos > self._length:
link_dict.append(data)
else:
# 构造新节点
new_code = Node(data)
# 构造游标
cur = self._head
# 构造计数器
cnt = 0
while cur.next is not None:
if cnt == pos:
# 让新节点有所指向
new_code.next = cur.next
# 让与新节点有关的节点有所指向
cur.next = new_code
self._length += 1
return
else:
# 移动游标
cur = cur.next
# 计数器加1
cnt += 1
else:
print("pos位置无效, 请确认")
exit()
def is_empty(self):
if self._length == 0:
print("链表为空")
return True
else:
return False
def remove(self, data):
if link_dict.is_empty():
return True
else:
cur = self._head
while cur.next is not None:
if cur.next.data == data:
# 删除节点
cur.next = cur.next.next
self._length -= 1
return
else:
# 游标移动
cur = cur.next
else:
print("data is not in link_data")
if __name__ == "__main__":
link_dict = LinkDict()
print("尾 部 添 加: ", end="")
for i in range(10):
link_dict.append(i)
link_dict.traval()
print("任意位置添加: ", end="")
link_dict.insert(-1, "a")
link_dict.insert(100, "z")
link_dict.insert(6, "x")
link_dict.traval()
print("删 除 节 点: ", end="")
link_dict.remove("a")
link_dict.remove("x")
link_dict.remove("z")
link_dict.traval()C:\Users\Amber\AppData\Local\Programs\Python\Python36\python.exe C:/Python/Exercises/CH03_02.1.py
尾 部 添 加: 0 --->1 --->2 --->3 --->4 --->5 --->6 --->7 --->8 --->9 --->None:now is terminal
任意位置添加: a --->0 --->1 --->2 --->3 --->4 --->x --->5 --->6 --->7 --->8 --->9 --->z --->None:now is terminal
删 除 节 点: 0 --->1 --->2 --->3 --->4 --->5 --->6 --->7 --->8 --->9 --->None:now is terminal
import sys
class employee:
def __init__(self):
self.num=0
self.slary=0
=''
self.next=None
def findnode(head,num):
ptr = head
while ptr != None:
if ptr.num==num:
return ptr
ptr=ptr.next
return ptr
def InsertNode(head,ptr,num,salary,name):
InsertNode=employee()
if not InsertNode:
return None
InsertNode.num=num
InsertNode.salary=salary
Insert=name
InsertNode.next=None
if ptr==None: #插入第一个节点
InsertNode.next=head
return InsertNode
else:
if ptr.next==None: #插入最后一个节点
ptr.next=InsertNode1041
else: #插入中间节点
InsertNode.next=ptr.next
ptr.next=InsertNode
return head
position = 0
data=[[1001,32367],[1002,24388],[1003,27556],[1007,31299],[1012,42660],[1014,25676],[1018,44145],[1043,52182],\
[1031,32769],[1037,21100],[1041,32196],[1046,25776]]
namedata=['Allen','Scott','Marry','John','Mark','Ricky','Lisa','Jessica','Hanson','Amy','Bob','Jack']
print('员工编号 薪水 员工编号 薪水 员工编号 薪水 员工编号 薪水')
print('--------------------------------------------------------------')
for i in range(3):
for j in range(4):
print('[%4d] $%d' %(data[j*3+i][0],data[j*3+i][1]),end='\t')
print()
print('--------------------------------------------------------------')
head = employee() #建立链表的头部
head.next=None
if not head:
print('Error!! 内存分配失败!!\n')
sys.exit(1)
head.num=data[0][0]
=namedata[0]
head.salary=data[0][1]
head.next=None
ptr=head
for i in range(1,12): #建立链表
newnode=employee()
newnode.next=None
newnode.num=data[i][0]
=namedata[i]
newnode.slary=data[i][1]
newnode.next=None
ptr.next=newnode
ptr=ptr.next
while (True):
print('请输入要插入其后的员工编号,如输入的编号不在此链表中')
position=int(input('新输入的员工节点将视为此链表的链表头部,要结束插入过程,请输入-1'))
if position==-1:
break
else:
ptr=findnode(head,position)
new_num=int(input('请输入新插入的员工编号:'))
new_salary=int(input('请输入新插入的员工薪水:'))
new_name=input('请输入新插入的员工姓名:')
head=InsertNode(head,ptr,new_num,new_salary,new_name)
print()
ptr=head
print('\t 员工编号 姓名\t 薪水')
print('\t=========================================================')
while ptr!=None:
print('\t[%2d]\t[ %-7s]\t[%3d]'%(ptr.num,,ptr.salary))
ptr=ptr.nextC:\Users\Amber\AppData\Local\Programs\Python\Python36\python.exe C:/Python/Exercises/CH03_02.py
员工编号 薪水 员工编号 薪水 员工编号 薪水 员工编号 薪水
--------------------------------------------------------------
[1001] $32367 [1007] $31299 [1018] $44145 [1037] $21100
[1002] $24388 [1012] $42660 [1043] $52182 [1041] $32196
[1003] $27556 [1014] $25676 [1031] $32769 [1046] $25776
--------------------------------------------------------------
请输入要插入其后的员工编号,如输入的编号不在此链表中
新输入的员工节点将视为此链表的链表头部,要结束插入过程,请输入-11003
请输入新插入的员工编号:1088
请输入新插入的员工薪水:55555
请输入新插入的员工姓名:jjjjj
以上程序还有待改善,执行有bug
import sys
class employee:
def __init__(self):
self.num=0
self.slary=0
=''
self.next=None
def del_ptr(head,ptr): #删除节点子程序
top=head
if ptr.num==head.num: #Case1:要删除的节点在链表头部
head=head.num
print('已删除第%d号员工姓名:%s 薪资:%d'%(ptr.num,,ptr.salary))
else:
while top.next!=ptr: #找到删除节点的前一个位置
top=top.next
if ptr.next==None: #删除在链表末尾的节点
top.next=None
print('已删除第%d号员工姓名:%s 薪资:%d' % (ptr.num, , ptr.salary))
else:
top.next=ptr.next #删除在列表中的任一节点
print('已删除第%d号员工姓名:%s 薪资:%d' % (ptr.num, , ptr.salary))
return head #返回链表
def main():
findword=0
namedata = ['Allen', 'Scott', 'Marry', 'John', 'Mark', 'Ricky', 'Lisa', 'Jessica', 'Hanson', 'Amy', 'Bob', 'Jack']
data = [[1001, 32367], [1002, 24388], [1003, 27556], [1007, 31299], [1012, 42660], [1014, 25676], [1018, 44145],
[1043, 52182], \
[1031, 32769], [1037, 21100], [1041, 32196], [1046, 25776]]
print('员工编号 薪水 员工编号 薪水 员工编号 薪水 员工编号 薪水')
print('--------------------------------------------------------------')
for i in range(3):
for j in range(4):
print('%2d [%3d] ' % (data[j * 3 + i][0], data[j * 3 + i][1]), end='')
print()
head = employee() #建立链表头部
if not head:
print('Error!! 内存分配失败!!\n')
sys.exit(0)
head.num = data[0][0]
= namedata[0]
head.salary = data[0][1]
head.next = None
ptr = head
for i in range(1, 12): # 建立链表
newnode = employee()
newnode.num = data[i][0]
= namedata[i]
newnode.slary = data[i][1]
newnode.num=data[i][0]
newnode.next = None
ptr.next = newnode
ptr = ptr.next
while (True):
findword=int(input('请输入要删除的员工编号,要结束删除过程,请输入-1'))
if (findword == -1):
break
else:
ptr=head
find = 0
while ptr != None:
if ptr.num==findword:
ptr=del_ptr(head,ptr)
find = find+1
head = ptr
ptr=ptr.next
if find == 0:
print('#######没有找到#######')
ptr = head
print('\t员工编号 姓名\t薪水') #打印剩余链表中的数据
print('\t=======================================================')
while(ptr!=None):
print('\t[%2d]\t[ %-10s]\t[%3d]' % (ptr.num, , ptr.salary))
ptr=ptr.nextmain()以上程序还有待改善,执行有bug
# CH03_04.py
# 将员工数据的链表节点按照员工工号反转打印出来
# include <stdio.h>
# include <stdlib.h>
class employee:
def __init__(self):
self.num = 0
self.salary = 0
= ''
self.next = None
findword = 0
namedata = ['Allen', 'Scott', 'Marry', 'John', 'Mark', 'Ricky', 'Lisa', 'Jassica', 'Hanson', 'Amy', 'Bob', 'Jack']
data = [[1001,32367],[1002,24388],[1003,27556],[1007,31299],[1012,42660],[1014,25676],[1018,44145],[1043,52182],[1031,32769],[1037,21100],[1041,32196],[1046,25776]]
head = employee() #建立链表的头部
if not head:
print('Error!! Memory Allocation Failed!!')
sys.exit(0)
head.num = data[0][0]
=namedata[0]
head.salary=data[0][1]
head.next = None
ptr = head
for i in range(1,12): #建立链表
newnode=employee()
newnode.num=data[i][0]
=namedata[i]
newnode.salary=data[i][1]
newnode.next=None
ptr.next=newnode
ptr=ptr.next
ptr=head
i = 0
print('反转前的员工链表节点数据:')
while ptr != None: #打印链表数据
print('[%2d %6s %3d] => ' %(ptr.num,,ptr.salary),end='')
i=i+1
if i >= 3: # 三个元素为一行
print()
i=0
ptr=ptr.next
ptr=head
before=None
print('\n反转后的员工链表节点数据:')
while ptr != None: #链表反转,利用三个指针
last = before
before = ptr
ptr = ptr.next
before.next = last
ptr = before
while ptr != None:
print('[%2d %6s %3d] => ' %(ptr.num,,ptr.salary),end='')
i=i+1
if i >= 3: # 三个元素为一行
print()
i=0
ptr=ptr.nextC:\Users\Amber\AppData\Local\Programs\Python\Python36\python.exe C:/Python/Exercises/CH03_04.py
反转前的员工链表节点数据:
[1001 Allen 32367] => [1002 Scott 24388] => [1003 Marry 27556] =>
[1007 John 31299] => [1012 Mark 42660] => [1014 Ricky 25676] =>
[1018 Lisa 44145] => [1043 Jassica 52182] => [1031 Hanson 32769] =>
[1037 Amy 21100] => [1041 Bob 32196] => [1046 Jack 25776] =>
反转后的员工链表节点数据:
[1046 Jack 25776] => [1041 Bob 32196] => [1037 Amy 21100] =>
[1031 Hanson 32769] => [1043 Jassica 52182] => [1018 Lisa 44145] =>
[1014 Ricky 25676] => [1012 Mark 42660] => [1007 John 31299] =>
[1003 Marry 27556] => [1002 Scott 24388] => [1001 Allen 32367] =>
Process finished with exit code 0
# 连接两个链表
import sys
import random
def concatlist(ptr1,ptr2):
ptr = ptr1
while ptr.next != None:
ptr=ptr.next
ptr.next = ptr2
return ptr1
class employee:
def __init__(self):
self.num=0
self.salary=0
=''
self.next=None
findword=0
data = [[None] * 2 for row in range(12)]
namedata1=['Allen','Scott','Marry','Jon','Mark','Ricky','Lisa','Jassica','Hanson','Amy','Bob','Jack']
namedata2=['May','John','Michael','Andy','Tom','Jane','Yoko','Axel','Alex','Judy','Kelly','Lucy']
for i in range(12):
data[i][0]=i+1
data[i][1]=random.randint(51,100)
head1=employee() #建立第一组链表的头部
if not head1:
print('Error!! Memory Allocation Failed!!')
sys.exit(0)
head1.num=data[0][0]
head1.name=namedata1[0]
head1.salary=data[0][1]
head1.next=None
ptr = head1
for i in range(1,12): #建立第一组链表
newnode=employee()
newnode.num=data[i][0]
=namedata1[i]
newnode.salary=data[i][1]
newnode.next=None
ptr.next=newnode
ptr=ptr.next
for i in range(1,12):
data[i][0] = i+13
data[i][1]=random.randint(51,100)
head2=employee() #建立第2组链表的头部
if not head2:
print('Error!! Memory Allocation Failed!!')
sys.exit(0)
head2.num=data[0][0]
head2.name=namedata2[0]
head2.salary=data[0][1]
head2.next=None
ptr = head2
for i in range(1,12): #建立第2组链表
newnode=employee()
newnode.num=data[i][0]
=namedata2[i]
newnode.salary=data[i][1]
newnode.next=None
ptr.next=newnode
ptr=ptr.next
i=0
ptr=concatlist(head1,head2) #将链表相连
print('两个链表相连的结果为: ')
while ptr!=None:
print('[%2d %6s %3d] => '%(ptr.num,,ptr.salary),end='')
i=i+1
if i>=3:
print()
i=0
ptr=ptr.nextC:\Users\Amber\AppData\Local\Programs\Python\Python36\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 181.2784.25\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 49898 --file C:/Users/Amber/Desktop/CH03_05.py
pydev debugger: process 23232 is connecting
Connected to pydev debugger (build 181.2784.25)
两个链表相连的结果为:
[ 1 Allen 64] => [ 2 Scott 94] => [ 3 Marry 100] =>
[ 4 Jon 96] => [ 5 Mark 52] => [ 6 Ricky 80] =>
[ 7 Lisa 86] => [ 8 Jassica 79] => [ 9 Hanson 79] =>
[10 Amy 78] => [11 Bob 87] => [12 Jack 56] =>
[ 1 May 64] => [14 John 71] => [15 Michael 98] =>
[16 Andy 71] => [17 Tom 59] => [18 Jane 93] =>
[19 Yoko 60] => [20 Axel 72] => [21 Alex 82] =>
[22 Judy 57] => [23 Kelly 99] => [24 Lucy 58] =>
# CH03_06
# 建立5个学生成绩单的单向链表,然后遍历每一个节点并打印学生的姓名与成绩
class student:
def __init__(self):
self.num=0
=''
self.score=0
self.next=None
print('请输入5项学生数据: ')
node = student()
if not node:
print('[Error!! Memory allocate Failed!!]')
sys.exit(0)
node.num=eval(input('请输入学号:'))
=input('请输入姓名:')
node.score=eval(input('请输入成绩:'))
ptr = node # 保留链表头部,以ptr为当前节点指针
for i in range(1,5):
newnode = student() #建立新节点
if not newnode:
print('[Error!! Memory Allocate Failed!!]')
sys.exit(0)
newnode.num=eval(input('请输入学号:'))
=input('请输入姓名:')
newnode.score=int(input('请输入成绩:'))
newnode.next=None
ptr.next=newnode #把新节点加在链表后面
ptr=ptr.next #让ptr保持在链表的最后面
print('学生成绩')
print('学号\t姓名\t成绩\n==============================================')
ptr=node #让ptr回到链表头部
while ptr != None:
print('%3d\t%-s\t%3d'%(ptr.num,,ptr.score))
node=ptr
ptr=ptr.next #ptr按序往后遍历链表1# CH03_07.py
# 两个多项式求和
class LinkedList: #声明链表结构
def __init__(self):
self.coef=0
self.exp=0
self.next=None
def create_link(data): #建立多项式子程序
for i in range(4):
newnode=LinkedList()
if not newnode:
print('Error!! Memory Allocation Failed!!')
sys.exit(0)
if i == 0:
newnode.coef=data[i]
newnode.exp=3-i
newnode.next=None
ptr=head
elif data[i] != 0:
newnode.coef=data[i]
newnode.exp = 3 - i
newnode.next = None
ptr = newnode
return head
def print_link(head):
while head != None:
if head.exp==1 and head.coef!=0:
print('%dX+'%(head.coef),end='')
elif head.exp!=0 and head.coef!=0:
print('%dX^%d+'%(head.coef,head.exp),end='')
elif head.coef!=0:
print('%d'%(head.coef))
head=head.next
print()
def sum_link(a,b):
i=0
ptr=b
plus=[None]*4
while a!=None:
if a.exp==b.exp:
plus[i]=a.coef+b.coef
a=a.next
b=b.next
i=i+1
elif b.exp>a.exp:
plus[i]=b.coef
i=i+1
elif a.exp>b.exp:
plus[i]=a.coef
a=a.next
i=i+1
return create_link(plus)
def main():
data1 = [3,0,4,2]
data2 = [6,8,6,9]
print("原始多项式:\nA=",end='')
a=create_link(data1)
b=create_link(data2)
print_link(a)
print('B=',end='')
print_link(b)
print("多项式相加的结果:\nC=",end='')
print_link(sum_link(a,b))
main()第二节:环形链表
class student:
def __init__(self):
=''
self.no=''
self.next=None
head=student() #新增链表头位置
ptr=head #设置存取指针位置
ptr.next=None #目前无下一元素
select=0
while select!=2:
select=int(input('(1)新增 (2)离开'))
if select == 2:
break
=input('xingming:')
ptr.no=input('xuehao:')
new_data=student() #新增下一个元素
ptr.next=new_data #连接下一个元素
new_data.next=None #下一个元素的next先设置为None
ptr=new_data #存取指针设置为新元素所在位置
ptr.next=head #设置从指针头开始
print()
ptr=head
while True:
print('xingming:%s\txuehao:%s\n'%(,ptr.no))
ptr=ptr.next #将head移动到下一个元素
if ptr.next==head:
break
print('---------------------------------------------------------------------------')
C:\Users\Amber\AppData\Local\Programs\Python\Python36\python.exe C:/Users/Amber/Desktop/CH03_08.py
(1)新增 (2)离开1
xingming:jim
xuehao:1
(1)新增 (2)离开1
xingming:tom
xuehao:2
(1)新增 (2)离开2
xingming:jim xuehao:1
xingming:tom xuehao:2
---------------------------------------------------------------------------
Process finished with exit code 0
















