zoukankan      html  css  js  c++  java
  • 2019.9.19-双向链表及添加元素代码

    # coding:utf-8

    class Node(object):
    """結點"""
    def __init__(self, item):
    self.elem = item
    self.next = None
    self.pre = None


    class DoubuleLinkList(object):
    """雙向鏈表"""
    # def __init__(self, node=None):
    # self.__head = node
    #
    # def is_empty(self):
    # """鏈表是否爲空"""
    return self.__head == None

    def length(self):
    """鏈表長度"""
    cur遊樸,用來移動遍歷節點
    cur = self.__head
    count記錄數量
    count = 0
    while cur != None:
    count += 1
    cur = cur.next
    return count

    def travel(self):
    """遍歷整個鏈表"""
    cur = self.__head
    while cur != None:
    print(cur.elem, end=" ")
    cur = cur.next
    print("")

    def add(self, item):
    """鏈表頭部添加元素,頭插法"""
    node = Node(item)
    node.next = self.__head
    self.__head = node
    node.next.prev = node

    def append(self, item):
    """鏈表尾部添加元素,尾插法"""
    node = Node(item)
    if self.is_empty():
    self.__head = node
    else:
    cur = self.__head
    while cur.next != None:
    cur = cur.next
    cur.next = node
    node.prev = cur

    def insert(self, pos, item):
    """指定位置添加元素
    :param pos 從0開始
    """
    if pos <= 0:
    self.add(item)
    elif pos > (self.length()-1):
    self.append(item)
    else:
    cur = self.__head
    count = 0
    while count < pos:
    count += 1
    cur = cur.next
    # 當循環退出後,cur指向pos位置
    node = Node(item)
    node.next = cur
    node.next = cur.prev
    cur.prev.next = node
    cur.prev = node

    def remove(self, item):
    """刪除節點"""
    cur = self.__head
    pre = None
    while cur != None:
    if cur.elem == item:
    # 先判斷此結點是否是頭節點
    # 頭節點
    if cur == self.__head:
    self.__head = cur.next
    else:
    pre.next = cur.next
    break
    else:
    pre = cur
    cur = cur.next

    def search(self, item):
    """查找節點是否存在"""
    cur = self.__head
    while cur != None:
    if cur.elem == item:
    return True
    else:
    cur = cur.next
    return False

    if __name__ == "__main__":
    dll = DoubuleLinkList()

     

     

     

  • 相关阅读:
    使用公钥登录SSL
    javascript看你能够做对几题
    windows 与fedora时间差
    Linux 启动直接进入 console,
    fedora -- java多版本切换
    fedora 解决yumBackend.py进程CPU占用过高
    fedora 禁止nouveau加载
    联邦学习中的隐私研究
    优秀博客链接
    【论文学习11】GIANT: Globally Improved Approximate Newton Method for Distributed Optimization
  • 原文地址:https://www.cnblogs.com/lishuide/p/11546497.html
Copyright © 2011-2022 走看看