zoukankan      html  css  js  c++  java
  • python实现双向链表

    废话不多说,直接贴代码(python 3.6.7):

    #-*-coding=utf-8-*-
    class Node(object):
    """结点"""
    def __init__(self,item):
    self.elem=item
    self.next=None
    self.prev=None

    class DoubleLinkList(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:
    cur=cur.next
    count+=1
    return count

    def travel(self):
    """遍历整个链表"""
    cur=self.__head
    while cur!=None:
    print(cur.elem)
    cur=cur.next

    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):
    """指定位置添加元素"""
    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
    node=Node(item)
    node.next=cur
    node.prev=cur.prev
    cur.prev.next=node
    cur.prev=node


    def remove(self,item):
    """删除节点"""
    cur=self.__head

    while cur!=None:
    if cur.elem==item:
    if cur==self.__head:
    self.__head=cur.next
    if cur.next:
    cur.next.prev=None
    else:
    cur.prev.next=cur.next
    cur.next.prev=cur.prev
    break
    else:
    cur=cur.next


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

    if __name__=="__main__":
    dll=DoubleLinkList()
    print(dll.is_empty())
    print(dll.length())
    dll.append(1)
    print(dll.is_empty())
    print(dll.length())
    dll.append(2)
    dll.add(8)
    dll.append(3)
    dll.append(4)
    dll.append(5)
    dll.append(6)
    dll.append(7)
    dll.append(8)
    dll.travel()
    dll.insert(3,100)
    dll.travel()
    dll.remove(8)
    dll.travel()
    dll.travel()
    dll.remove(100)
    dll.insert(100,200)
    dll.travel()


  • 相关阅读:
    [BZOJ] 1611: [Usaco2008 Feb]Meteor Shower流星雨
    [BZOJ] 1626: [Usaco2007 Dec]Building Roads 修建道路
    [BZOJ] 1616: [Usaco2008 Mar]Cow Travelling游荡的奶牛
    [BZOJ] 1627: [Usaco2007 Dec]穿越泥地
    [BZOJ] 1614: [Usaco2007 Jan]Telephone Lines架设电话线
    [BZOJ] 1617: [Usaco2008 Mar]River Crossing渡河问题
    [BZOJ] 1612: [Usaco2008 Jan]Cow Contest奶牛的比赛
    [BZOJ] 1625: [Usaco2007 Dec]宝石手镯
    [BZOJ] 1606: [Usaco2008 Dec]Hay For Sale 购买干草
    [HDU] 迷宫城堡 HDU
  • 原文地址:https://www.cnblogs.com/linwenbin/p/10358947.html
Copyright © 2011-2022 走看看