Python - 实现简单单链表
2017-08-22 16:18
495 查看
代码如下:
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
class Node(): def __init__(self,pvalue,pnext = None): self.pvalue = pvalue self.pnext = pnext def 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 root def PrintLinkedList(head): p = head while p != None: print(p.pvalue) p = p.pnext def LenLinkedList(head): p = head c = 0 while p != None: c += 1 p = p.pnext return c def InsertLinkedList(head,n): if n < 1 or n > LenLinkedList(head): 4000 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 head def 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 head if __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
相关文章推荐
- 数据结构与算法之链表的Python简单实现
- 用 Python实现链表的翻转,奇偶下标修改(利用数组,非常简单)
- Python数据结构与算法之列表(链表,linked list)简单实现
- Python 实现简单的单向链表
- Python 用Redis简单实现分布式爬虫的方法
- python实现单链表,及两个链表按位相加
- 《Python-yield的简单练习》---yield实现单线程下的并行
- python实现单向链表
- 使用shell和python分别实现简单菜单功能--打印当前系统状态信息
- python实现一个简单的rrdtool
- Python实现简单的WEB服务器
- C语言实现一个简单的单向链表list
- python实现简单爬虫功能
- python简单实现拉格朗日差值计算
- 小白入门python之在命令框中实现简单的python代码
- PHP简单实现循环链表功能示例
- 【python初学】仿射加密的简单实现
- BeautifulSoup与正则_简单爬虫python3实现
- Python实现简单的API
- [python]rsa加密算法的一个简单实现