码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现单链表

时间:2015-09-30 12:44:23      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:

#! /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()

 

python 实现单链表

标签:

原文地址:http://www.cnblogs.com/allenhaozi/p/4848704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!