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

Python模拟 堆栈,队列,链表

时间:2019-01-04 21:23:48      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:pen   ast   nod   记录   none   col   else   返回   exce   

1. 堆栈

class my_stack(object):
    def __init__(self, value):
        self.value = value
        # 前驱
        self.before = None
        # 后继
        self.behind = None

    def __str__(self):
        return str(self.value)


def top(stack):
    if isinstance(stack, my_stack):   # 判断对象是否合法
        if stack.behind is not None:  # 如果behind属性不为空
            return top(stack.behind)     # 模拟对象的连接,直至找到为空的对象,并返回
        else:
            return stack                # 如果behind 为空,返回其


def push(stack, ele):  # 进栈
    push_ele = my_stack(ele)      # 实例对象 push_ele
    if isinstance(stack, my_stack):     
        stack_top = top(stack)        # 得到一个behind为空的对象
        push_ele.before = stack_top        # push_ele 的前驱 before 连接 stack对象
        push_ele.before.behind = push_ele  # stack对象的后继 behind 连接 push_ele
    else:
        raise Exception(不要乱扔东西进来好么)    # 非法对象


def pop(stack):  # 出栈
    if isinstance(stack, my_stack):     # 判断对象是否合法
        stack_top = top(stack)          # 得到一个behind为空的对象
        if stack_top.before is not None:    # 如果其前驱不为空,代表连接了对象
            stack_top.before.behind = None  # 前驱连接的后继设为空
            stack_top.behind = None            # 后继设为空
            return stack_top
        else:
            print(已经是栈顶了)            # 前驱为None,代表空栈

 

2. 队列

class MyQueue():
    def __init__(self, value=None):
        self.value = value
        # 前驱
        self.before = None
        # 后继
        self.behind = None

    def __str__(self):
        if self.value is not None:
            return str(self.value)
        else:
            return None

def create_queue():
    """仅有队头"""
    return MyQueue()        # 实例

def last(queue):
    if isinstance(queue, MyQueue):
        if queue.behind is not None:        # 返回一个后继为空的对象,不为空继续找
            return last(queue.behind)
        else:
            return queue

def push(queue, ele):    # 入列
    if isinstance(queue, MyQueue):
        last_queue = last(queue)
        new_queue = MyQueue(ele)
        last_queue.behind = new_queue        # new_queue连接last(queue)的后继

def pop(queue):            # 出列
    if queue.behind is not None:                
        get_queue = queue.behind
        queue.behind = queue.behind.behind        # queue.behind不为空时连接下一个对象的后继
        return get_queue
    else:
        print(队列里已经没有元素了)

def print_queue(queue):
    print(queue)
    if queue.behind is not None:
        print_queue(queue.behind)

 

3. 双端队列

class Deque:
    """模拟双端队列"""
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def addFront(self, item):
        self.items.append(item)        # 添加到最后

    def addRear(self, item):
        self.items.insert(0, item)        # 插入到第一

    def removeFront(self):
        return self.items.pop()        # 删除最后一个

    def removeRear(self):
        return self.items.pop(0)        # 删除第一个

    def size(self):
        return len(self.items)    
    

 

4. 优先级队列

import queue as Q

class Skill(object):
    def __init__(self, priority, description):
        self.priority = priority
        self.description = description

    def __lt__(self, other):
        return self.priority < other.priority

    def __str__(self):
        return ( + str(self.priority) + ,\‘ + self.description + \‘)


def PriorityQueue_class():
    que = Q.PriorityQueue()        # 优先级队列
    que.put(Skill(7, proficient7))    # 第一个参数作为判断
    que.put(Skill(5, proficient5))
    que.put(Skill(6, proficient6))
    que.put(Skill(10, expert))
    que.put(Skill(1, novice))
    print(end)
    while not que.empty():
        print(que.get())


PriorityQueue_class()

 

5. 单向链表

class Node(object):
    def __init__(self, value):
        # 元素域
        self.value = value    # 变量
        # 链接域
        self.next = None    # 指针


class LinkedListOneway(object):            # 单向链表
    def __init__(self, node=None):
        self.__head = node

    def __len__(self):
        # 游标,用来遍历链表
        cur = self.__head
        # 记录遍历次数
        count = 0
        # 当前节点为None则说明已经遍历完毕
        while cur:
            count += 1
            cur = cur.next        # cur.next 指向None ,遍历完成,循环结束
        return count    

    def is_empty(self):
        # 头节点不为None则不为空
        return self.__head == None

    def add(self, value):
        """
        头插法
        先让新节点的next指向头节点
        再将头节点替换为新节点
        顺序不可错,要先保证原链表的链不断,否则头节点后面的链会丢失
        """
        node = Node(value)
        node.next = self.__head
        self.__head = node

    def append(self, value):
        """尾插法"""
        node = Node(value)
        cur = self.__head
        if self.is_empty():
            self.__head = node
        else:
            while cur.next:
                cur = cur.next
            cur.next = node

    def insert(self, pos, value):
        # 应对特殊情况
        if pos <= 0:
            self.add(value)
        elif pos > len(self) - 1:
            self.append(value)
        else:
            node = Node(value)
            prior = self.__head
            count = 0
            # 在插入位置的前一个节点停下
            while count < (pos - 1):
                prior = prior.next
                count += 1
            # 先将插入节点与节点后的节点连接,防止链表断掉,先链接后面的,再链接前面的
            node.next = prior.next
            prior.next = node

    def remove(self, value):
        cur = self.__head
        prior = None
        while cur:
            if value == cur.value:
                # 判断此节点是否是头节点
                if cur == self.__head:
                    self.__head = cur.next
                else:
                    prior.next = cur.next
                break
            # 还没找到节点,有继续遍历
            else:
                prior = cur
                cur = cur.next

    def search(self, value):
        cur = self.__head
        while cur:
            if value == cur.value:
                return True
            cur = cur.next
        return False

    def traverse(self):
        cur = self.__head
        while cur:
            print(cur.value)
            cur = cur.next

 

6. 双向链表

class LinkedList():
    def __init__(self, value=None):
        self.value = value
        # 前驱
        self.before = None
        # 后继
        self.behind = None

    def __str__(self):
        if self.value is not None:
            return str(self.value)
        else:
            return None

def init():
    return LinkedList(HEAD)

def delete(linked_list):
    if isinstance(linked_list, LinkedList):
        if linked_list.behind is not None:
            delete(linked_list.behind)
            linked_list.behind = None
            linked_list.before = None
        linked_list.value = None

def insert(linked_list, index, node):
    node = LinkedList(node)
    if isinstance(linked_list, LinkedList):
        i = 0
        while linked_list.behind is not None:
            if i == index:
                break
            i += 1
            linked_list = linked_list.behind
        if linked_list.behind is not None:
            node.behind = linked_list.behind
            linked_list.behind.before = node
        node.before, linked_list.behind = linked_list, node

def remove(linked_list, index):
    if isinstance(linked_list, LinkedList):
        i = 0
        while linked_list.behind is not None:
            if i == index:
                break
            i += 1
            linked_list = linked_list.behind
        if linked_list.behind is not None:
            linked_list.behind.before = linked_list.before
        if linked_list.before is not None:
            linked_list.before.behind = linked_list.behind
        linked_list.behind = None
        linked_list.before = None
        linked_list.value = None

def trave(linked_list):
    if isinstance(linked_list, LinkedList):
        print(linked_list)
        if linked_list.behind is not None:
            trave(linked_list.behind)

def find(linked_list, index):
    if isinstance(linked_list, LinkedList):
        i = 0
        while linked_list.behind is not None:
            if i == index:
                return linked_list
            i += 1
            linked_list = linked_list.behind
        else:
            if i < index:
                raise Exception(404)
            return linked_list

 

Python模拟 堆栈,队列,链表

标签:pen   ast   nod   记录   none   col   else   返回   exce   

原文地址:https://www.cnblogs.com/wang-kai-1994/p/10222213.html

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