python实现链表
来源:互联网 发布:纯k线源码 编辑:程序博客网 时间:2024/06/03 15:42
刚学不久python,来实现一下单链表
网上拉的图:
下面是代码了:
#!/usr/bin/python# -*- coding: utf-8 -*-#__author__ = 'Mr Cai'class Node(object): '''节点''' def __init__(self,val,p = 0): self.data = val self.next = pclass LinkList(object): '''单链表类''' def __init__(self): self.head = 0 def initlist (self,data): '''初始化列表''' #创建头节点,next为0 self.head = Node(data[0]) p = self.head for item in data[1:]: node = Node(item) p.next = node p = node def getlength(self): '''获取链表长度''' if self.head == 0: return 0 p = self.head length = 1 while p.next != 0: p = p.next length += 1 return length def IsEmpty(self): '''判断链表是否是空,布尔型''' if self.head == 0: return True else: return False def clear(self): '''清空列表''' self.head = 0 def append(self,item): '''尾部加入元素''' if self.head == 0: self.head = Node(item) p = self.head while p.next != 0: p = p.next node = Node(item) p.next = node def getitem(self,index): '''给位置,打印元素''' if self.IsEmpty() : print 'The List is empty!' return if index < 0 or index > self.getlength() : print 'The index is error!' return p = self.head for i in range(0,index): p = p.next print p.data def insert(self,item,index): '''插入元素''' if self.IsEmpty(): print 'The list is empty' return if index < 0 or index > self.getlength() : print 'The index is error!' return p = self.head for i in range(0,index - 1): p = p.next temp = p.next node = Node(item,temp) p.next = node def delete(self,index): '''删除元素''' if self.IsEmpty(): print 'The list is empty' return if index < 0 or index > self.getlength() : print 'The index is error!' return p = self.head for i in range(0,index - 1): p = p.next p.next = p.next.next def show(self): '''打印出当前链表中所有元素''' if self.IsEmpty(): print 'The list is empty' return p = self.head while p != 0 : print p.data p = p.nextif __name__ == '__main__' : List = LinkList() print List.IsEmpty() List.initlist([3,5,6,8]) # List.show() List.append(10) # List.show() # print List.getlength() # List.clear() # List.show() # List.insert(111,3) # List.show() # List.delete(2) # List.show()
0 0
- python实现链表
- Python实现链表
- python实现的链表
- Python 实现单向链表
- python实现的链表
- python实现单向链表
- python实现双向链表
- Python 实现单向链表
- Python链表的实现
- python实现链表增删
- Python 链表的实现
- 链表的python实现
- 用python实现链表
- jeseph问题,python实现, 循环链表
- Python 实现简单的单向链表
- Python 实现有序单向链表
- 用python实现链表操作
- Python 实现双向链表(图解)
- error: No resource identifier found for attribute 'showAsAction' in package 'com.example.singlecheck
- Android内存优化大全(中)
- C# .NET OCR and Barcode Recognition
- HTTP1.1中CHUNKED编码解析
- Kth Smallest Element in a BST
- python实现链表
- nyoj269VF
- GTK常用控件之窗口( GtkWindow )
- Linux设备驱动核心理论(二)
- bzoj2553: [BeiJing2011]禁忌
- easyUI的datagrid 分页保存选中状态
- Jetty和Tomcat的选择
- linux内核 asmlinkage宏
- 玩转Nodejs的集群