关闭

栈、队列和链表

标签: python链表class
126人阅读 评论(0) 收藏 举报
分类:

栈是一种后进先出的策略,其操作包括入栈,出栈,获取栈顶元素值等。
我们这里用python列表简单的模拟栈,考虑上下溢出的情况,其代码实现如下:

class Stack:
    def __init__(self,sz=65536):
        self.stack = []
        self.top = -1
        self.size = sz

    def isEmpty(self):
        return True if self.top is -1 else False

    def isFull(self):
        return True if self.top is self.size - 1 else False

    def push(self,obj): #压入栈操作
        if self.isFull():
            raise Exception("Stack over flow!")
        else:
            self.stack.append(obj)
            self.top += 1

    def pop(self): #弹出栈顶元素
        if self.isEmpty():
            raise Exception("Stack is empty!")
        else:
            self.top -= 1
            return self.stack.pop()

    def count(self): #获取栈中元素个数
        return self.top + 1

    def top(self): #获取栈顶元素值
        if self.isEmpty():
            raise Exception("Stack is empty!")
        return self.stack[top]

    def show(self):
        print(self.stack)

队列

队列是一种先进先出的数据结构,主要操作包括入队,出队。入队的元素加入到对尾,从队头取出出队的元素。这里用列表简单模拟队列,其实现如下:

class Queue:
    def __init__(self,sz=65535):
        self.queue = []
        self.size = sz
        self.len = 0

    def isEmpty(self):
        return True if self.len is 0 else False

    def isFull(self):
        return True if self.len is self.size else False

    def length(self):
        return self.len

    def enqueue(self,obj): #入队
        if self.isFull():
            raise Exception("Queue is Full!")
        else:
            self.queue.append(obj)
            self.len += 1

    def dequeue(self): #出队
        if self.isEmpty():
            raise Exception("Queue is Empty!")
        else:
            self.len -= 1
            return self.queue.pop(0)

    def show(self):
        print(self.queue)

实际应用中还使用一种叫做双端队列的数据结构,其实现也在队列的基础上变成可以对两端操作。

class Deque:
    def __init__(self,sz=65535):
        self.queue = []
        self.size = sz
        self.len = 0

    def isEmpty(self):
        return True if self.len is 0 else False

    def isFull(self):
        return True if self.len is self.size else False

    def length(self):
        return self.len

    def enqueue(self,obj): #从右边入队
        if self.isFull():
            raise Exception("DeQueue is Full!")
        else:
            self.len += 1
            self.queue.append(obj)

    def enqueueLeft(self,obj): #从左边入队
        if self.isFull():
            raise Exception("DeQueue is Full!")
        else:
            self.len += 1
            self.queue.insert(0,obj)

    def dequeue(self): #从左边出队
        if self.isEmpty():
            raise Exception("DeQueue is Empty!")
        else:
            self.len -= 1
            return self.queue.pop(0)

    def dequeueRight(self): #从右边出队
        if self.isEmpty():
            raise Exception("DeQueue is Empty!")
        else:
            self.len -= 1
            return self.queue.pop()

    def show(self):
        print(self.queue)

链表

链表分为单向链表和双向链表,这里给出双向链表的实现:

#构成双向链表的结点
class Node:
    def __init__(self,key=None):
        self.key = key
        self.prev = None #指向前驱
        self.next = None #指向后继

    def getKey(self):
        return self.key

    def getPrev(self):
        return self.prev

    def getNext(self):
        return self.next

    def setKey(self, key):
        self.key = key

    def setPrev(self, prev):
        self.prev = prev

    def setNext(self, next):
        self.next = next


class LinkList:
    def __init__(self,data=None):
        self.head = None
        self.len = 0
        if data:
            p = self.head = Node(data[0])
            self.len += 1
            for key in data[1:]:
                node = Node(key)
                p.setNext(node)
                node.setPrev(p)
                self.len += 1
                p = node
    #重载[]运算符,使其具体下标访问能力,比如像obj[1]这样访问           
    def __getitem__(self, index):
        if index >= self.len or index < 0:
            raise Exception("Index out of range!")
        else:
            p = self.head
            for i in range(index):
                p = p.getNext()
            return p.getKey()

    def length(self):
        return self.len

    def search(self,key):
        p = self.head
        while p and p.getKey() is not key:
            p = p.getNext()
        return p

    def insert(self,key):
        p = Node(key)
        if not self.head:
            self.head = p
            self.len += 1
        else:
            self.head.setPrev(p)
            p.setNext(self.head)
            self.head = p
            self.len += 1

    def delete(self,key):
        p = self.search(key)
        if p:
            if p.getPrev():
                p.getPrev().setNext(p.getNext())
            else:
                self.head = p.getNext()
            if p.getNext():
                p.getNext().setPrev(p.getPrev())
            p.setPrev(None)
            p.setNext(None)
            self.len -= 1

    def show(self):
        p = self.head
        while p:
            print(p.getKey(),end=' ')
            p = p.getNext()
        print()
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3741次
    • 积分:189
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类