python实现单链表_python 实现单链表

#! /usr/bin/env python

###### Linked List python implementation###### @reference Data Structures and Algorithm Analysis in C:Second Edition : Mark Allen Weiss### @date Tue Sep 29 20:51:55 CST 2015

#node structure

classNode(object):def __init__(self, value, p=None):

self.element=value

self.pNext=pclassLinkedList(object):def __init__(self):

self.head=NonedefmakeEmpty(self):

self.head=NonedefisEmpty(self):return self.head ==Nonedeffind(self, value):ifself.isEmpty():print 'the linked list is empty !'

returnp=self.headwhile p !=None:if p.element ==value:#the index of the target in linkedlist

returnp

p=p.pNextreturn -1

definsert(self, value):

item=Node(value)ifself.isEmpty():

self.head=itemelse:

p=self.headwhile p.pNext !=None:

p=p.pNext

p.pNext=itemdefdeleteList(self):ifself.isEmpty():print 'the linked list is empty !'

else:

p=self.head.pNext

self.head=Nonewhile p !=None:

tmp=p.pNext

p=None

p=tmpdefdelete(self, target):ifself.isEmpty():print 'the linked list is empty !'

else:

p=self.findPrevious(target)if notself.isLast(p):

tmpNode=p.pNext

p.pNext=tmpNode.pNext

tmpNode=Noneelse:

p.pNext=NonedefisLast(self,p):return p.pNext ==NonedeffindPrevious(self, target):ifself.isEmpty():print 'the linked list is empty !'

else:

p=self.headwhile p != None and p.pNext.element !=target:

p=p.pNextreturnpdefdebug(self):ifself.isEmpty():print 'the linked list is empty !'

else:

p=self.headwhile p !=None:printp.element

p=p.pNextif p ==None:print '-------------'

definitLinkedList(self,lists):for item inlists:

self.insert(item)

obj=LinkedList()

lists=[1,2,3,4,5,6,10,17]

obj.initLinkedList(lists)#rs=obj.isEmpty()#print rs#rs=obj.find(17)#print rs#rs=obj.isLast(rs)#print rs#obj.debug()#rs=obj.find(17)#rs=obj.find(14)#rs=obj.findPrevious(10)#print rs#print rs.element#obj.delete(10)

obj.deleteList()

obj.debug()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值