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 class Node(object): def __init__(self, value, p=None): self.element = value self.pNext = p class LinkedList(object): def __init__(self): self.head = None def makeEmpty(self): self.head = None def isEmpty(self): return self.head == None def find(self, value): if self.isEmpty(): print 'the linked list is empty !' return p = self.head while p != None: if p.element == value: #the index of the target in linkedlist return p p = p.pNext return -1 def insert(self, value): item = Node(value) if self.isEmpty(): self.head = item else: p = self.head while p.pNext != None: p = p.pNext p.pNext = item def deleteList(self): if self.isEmpty(): print 'the linked list is empty !' else: p = self.head.pNext self.head = None while p != None: tmp = p.pNext p = None p=tmp def delete(self, target): if self.isEmpty(): print 'the linked list is empty !' else: p = self.findPrevious(target) if not self.isLast(p): tmpNode = p.pNext p.pNext = tmpNode.pNext tmpNode = None else: p.pNext = None def isLast(self,p): return p.pNext == None def findPrevious(self, target): if self.isEmpty(): print 'the linked list is empty !' else: p = self.head while p != None and p.pNext.element != target: p = p.pNext return p def debug(self): if self.isEmpty(): print 'the linked list is empty !' else: p = self.head while p != None: print p.element p = p.pNext if p == None: print '-------------' def initLinkedList(self,lists): for item in lists: 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()