首页 > 代码库 > python单链表实例分享

python单链表实例分享

有关python单链表的实现代码。 

链表的定义:
链表(linked list)是由一组被称为结点的数据元素组成的数据结构,每个结点都包含结点本身的信息和指向下一个结点的地址。由于每个结点都包含了可以链接起来的地址信息,所以用一个变量就能够访问整个结点序列。也就是说,结点包含两部分信息:一部分用于存储数据元素的值,称为信息域;另一部分用于存储下一个数据元素地址的指针,称为指针域。链表中的第一个结点的地址存储在一个单独的结点中,称为头结点或首结点。链表中的最后一个结点没有后继元素,其指针域为空。  
python单链表实现代码:

#!/usr/bin/python# -*- coding: utf-8 -*-# www.jbxue.comclass Node(object):def __init__(self,val,p=0):self.data = valself.next = pclass LinkList(object):def __init__(self):self.head = 0def __getitem__(self, key):if self.is_empty():print linklist is empty.returnelif key <0 or key > self.getlength():print the given key is errorreturnelse:return self.getitem(key)def __setitem__(self, key, value):if self.is_empty():print linklist is empty.returnelif key <0 or key > self.getlength():print the given key is errorreturnelse:self.delete(key)return self.insert(key)def initlist(self,data):self.head = Node(data[0])p = self.headfor i in data[1:]:node = Node(i)p.next = nodep = p.nextdef getlength(self):p = self.headlength = 0while p!=0:length+=1p = p.nextreturn lengthdef is_empty(self):if self.getlength() ==0:return Trueelse:return Falsedef clear(self):self.head = 0def append(self,item):q = Node(item)if self.head ==0:self.head = qelse:p = self.headwhile p.next!=0:p = p.nextp.next = qdef getitem(self,index):if self.is_empty():print Linklist is empty.returnj = 0p = self.headwhile p.next!=0 and j <index:p = p.nextj+=1if j ==index:return p.dataelse:print target is not exist!def insert(self,index,item):if self.is_empty() or index<0 or index >self.getlength():print Linklist is empty.returnif index ==0:q = Node(item,self.head)self.head = qp = self.headpost = self.headj = 0while p.next!=0 and j<index:post = pp = p.nextj+=1if index ==j:q = Node(item,p)post.next = qq.next = pdef delete(self,index):if self.is_empty() or index<0 or index >self.getlength():print Linklist is empty.returnif index ==0:q = Node(item,self.head)self.head = qp = self.headpost = self.headj = 0while p.next!=0 and j<index:post = pp = p.nextj+=1if index ==j:post.next = p.nextdef index(self,value):if self.is_empty():print Linklist is empty.returnp = self.headi = 0while p.next!=0 and not p.data =http://www.mamicode.com/=value:p = p.nexti+=1if p.data =http://www.mamicode.com/= value:return ielse:return -1l = LinkList()l.initlist([1,2,3,4,5])print l.getitem(4)l.append(6)print l.getitem(5)l.insert(4,40)print l.getitem(3)print l.getitem(4)print l.getitem(5)l.delete(5)print l.getitem(5)l.index(5)

结果:

5
6
4
40
5
6

python单链表实例分享