python算法第四课感悟

python算法第四课感悟,第1张

单向循环链表

单链表的一个变形是单向循环链表,链表中最后一个节点的next域不再为None,而是指向链表的头节点。


实现代码

# coding:utf-8

class Node(object):
    """节点"""
    def __init__(self, elem):
        self.elem =elem
        self.next = None

class SingCycleLinst(object):
    """单向循环链表"""
    def __init__(self, node = None):
        self.__head = None
        if node:
            node.next=node

    def is_empty(self):
        """链表是否为空"""
        return self.__head == None

    def length(self):
        """链表长度"""
        if self.is_empty():
            return 0
        count = 1
        cur = self.__head
        # count 记录数量

        while cur.next != self.__head:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """遍历整个链表"""
        if self.is_empty():
            return
        cur = self.__head
        while cur.next != self.__head:
            print(cur.elem, end=" ")
            cur = cur.next
        # 退出循环,cur指向尾结点,但尾结点元素未打印,需要专门打印一次。


print(cur.elem) def add(self, item): """链表头部添加元素,头插法""" node = Node(item) if self.is_empty(): self.__head = node node.next =node else: cur = self.__head while cur.next != self.__head: cur = cur.next # 退出循环,cur指向尾结点,需要将尾结点指向头节点形成单向循环链表。


node.next = self.__head self.__head = node cur.next = node def append(self, item): """链表尾部添加元素,尾插法""" node = Node(item) if self.is_empty(): self.__head = node node.next =node else: cur = self.__head while cur.next != self.__head: cur = cur.next node.next = cur.next cur.next = node def insert(self, pos, item): """指定位置添加元素""" if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append() else: node = Node(item) cur = self.__head count = 0 while count < (pos -1): count += 1 cur = cur.next # 当循环退出后,cur指向pos-1位置 node.next = cur.next cur.next = node def remove(self, item): """删除节点""" if self.is_empty(): return cur = self.__head pre = None while cur.next != self.__head: if cur.elem == item: if cur == self.__head: # 头节点 # 找尾结点 rear = self.__head while rear.next != self.__head: rear = rear.next self.__head = cur.next rear.next = self.__head else: # 中间节点 pre.next = cur.next return else: pre = cur cur = cur.next # 退出循环,cur指向尾结点 if cur.elem == item: if cur == self.__head: self.__head = None else: pre.next = cur.next def search(self, item): """查找节点是否存在""" if self.is_empty(): return False cur = self.__head while cur != self.__head: if cur.elem == item: return True else: cur = cur.next if cur.elem == item: return True return False if __name__ == "__main__": scl = SingCycleLinst() print(scl.is_empty()) print(scl.length()) print() scl.append(1) scl.append(5) scl.append(45) scl.length() scl.travel() print() scl.add(74) scl.add(45265) scl.travel() scl.remove(5) scl.travel() scl.remove(45265) scl.travel()

栈和队列

栈——相当于单口容器——后进先出(LIFO, Last In First Out)

栈结构实现

栈可以用顺序表实现,也可以用链表实现。


以顺序表实现为例

# coding:utf-8

class Stack(object):
    """栈"""

    def __init__(self):
        self.__list = []

    def push(self, item):
        """添加一个新元素item到栈顶"""
        self.__list.append(item)

    def pop(self):
        """d出栈顶元素"""
        return self.__list.pop()

    def peek(self):
        """返回栈顶元素"""
        if self.__list:
            return self.__list[-1]

    def is_empty(self):
        """判断栈是否为空"""
        return self.__list == []

    def size(self):
        """返回栈的元素个数"""
        return len(self.__list)


if __name__ == "__main__":
    s = Stack()
    s.push(1)
    s.push(2)
    s.push(3)
    print(s.pop())
    print(s.pop())
    print(s.pop())

队列——先进先出(FIFO, First In First Out)

队列(queue)是只允许在一端进行插入 *** 作,而在另一端进行删除 *** 作的线性表。


队列结构实现

队列可以用顺序表实现,也可以用链表实现。


以顺序表实现为例

# coding:utf-8

class Queue(object):
    # 队列,先进先出。


def __init__(self): self.__list = [] def enqueue(self, item): """往队列中添加一个item元素""" self.__list.append(item) def dequeue(self): """从队列头部删除一个元素""" return self.__list.pop(0) def is_empty(self): """判断队列是否为空""" return self.__list == None def size(self): """返回队列的大小""" return len(self.__list) if __name__ == "__main__": q = Queue() print(q.is_empty()) print(q.size()) print() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) print() print(q.is_empty()) print(q.size()) print() print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.is_empty())

双端队列的实现

# coding:utf-8

class DoubleQueue(object):
    # 双端队列,先进先出。


def __init__(self): self.__list = [] def add_font(self, item): """往队列中添加一个item元素""" self.__list.insert(0, item) def add_rear(self, item): """往队列中添加一个item元素""" self.__list.append(item) def pop_front(self): """从队列头部删除一个元素""" return self.__list.pop(0) def pop_rear(self): """从队列尾部删除一个元素""" return self.__list.pop() def is_empty(self): """判断队列是否为空""" return self.__list == None def size(self): """返回队列的大小""" return len(self.__list) if __name__ == "__main__": dq = DoubleQueue() print("is_empty?:{0}".format(dq.is_empty())) print("Size:{0}".format(dq.size())) print() dq.add_font(1) dq.add_font(2) dq.add_font(3) dq.add_font(4) dq.add_font(5) dq.add_font(6) dq.add_font(7) dq.add_font(8) dq.add_font(9) dq.add_font(10) dq.add_rear(101) dq.add_rear(202) dq.add_rear(303) dq.add_rear(404) dq.add_rear(505) dq.add_rear(606) dq.add_rear(707) dq.add_rear(808) dq.add_rear(909) print() print("is_empty?:{0}".format(dq.is_empty())) print("Size:{0}".format(dq.size())) print() print(dq.pop_front(), end=" ") print(dq.pop_front(), end=" ") print(dq.pop_front(), end=" ") print(dq.pop_front(), end=" ") print("is_empty?:{0}".format(dq.is_empty())) print() print(dq.pop_rear(), end=" ") print(dq.pop_front(), end=" ") print(dq.pop_rear(), end= " ") print(dq.pop_rear(), end= " ") print(dq.pop_front(), end= " ") print(dq.pop_front(), end= " ") print(dq.pop_rear(), end= " ") print(dq.pop_rear(), end= " ") print("Size:{0}".format(dq.size())) print("is_empty?:{0}".format(dq.is_empty()))

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/568468.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存