Python
来源:互联网 发布:编程 开发 编辑:程序博客网 时间:2024/06/15 21:16
代码如下:
class Node(): def __init__(self,pvalue,pnext = None): self.pvalue = pvalue self.pnext = pnextdef CreateLinkedList(n): if n <= 0 : return False if n == 1 : return Node(1) else: root = Node(1) # init the root node tmp = root for i in range(2,n+1): tmp.pnext = Node(i) tmp = tmp.pnext return rootdef PrintLinkedList(head): p = head while p != None: print(p.pvalue) p = p.pnextdef LenLinkedList(head): p = head c = 0 while p != None: c += 1 p = p.pnext return cdef InsertLinkedList(head,n): if n < 1 or n > LenLinkedList(head): return False p = head for i in range(1,n-1): p = p.pnext v = int(input('Please input the number:')) t = Node(v) t.pnext = p.pnext p.pnext = t return headdef DeleteLinkedList(head,n): if n < 1 or n > LenLinkedList(head): return False elif n == 1: head = head.pnext else : p = head for i in range(1,n-1): p = p.pnext q = p.pnext p.pnext = q.pnext return headif __name__=='__main__': print("Create a linklist:") head = CreateLinkedList(5) PrintLinkedList(head) print("___________________________") print() n = int(input("Please input the index of insert:")) InsertLinkedList(head,n) PrintLinkedList(head) print("___________________________") print() n1 = int(input("Please input the index of delete:")) DeleteLinkedList(head,n1) PrintLinkedList(head) print("___________________________") print() print('The LinkedList\'s length is:{0}'.format(LenLinkedList(head)))
Result:
Create a linklist: 1 2 3 4 5
Please input the index of insert:2
Please input the number:34
1 34 2 3 4 5
Please input the index of delete:4
1 34 2 4 5
The LinkedList’s length is:5
阅读全文
0 0
- Python
- Python
- Python
- python
- Python
- PYTHON
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- python
- Python
- CISP国家注册信息安全专员
- ACM省赛海岛争霸(Dijkstra和DFS两种方法)
- TCP窗口控制、流控制、拥塞控制
- 物体检测“DSOD: Learning Deeply Supervised Object Detectors from Scratch”
- 扫雷
- Python
- 2017/08/23 备忘
- bzoj 3358: [Usaco2004 Jan]洪水
- 数据结构(一)-顺序存储结构的插入和删除:向指定位置的数组插入和删除元素
- Unity学习之路——C# 位操作、Flags、接口、抽象类
- flannel 概述
- ubuntu修改mysql默认路径和修改max_connect参数
- Spring boot 搭建个人博客系统(六)——文章点击量和阅读排行榜
- Android动画(一)-视图动画