python實現(xiàn)雙向鏈表基本結構及其基本方法

雙向鏈表是在單向鏈表的基礎上更為復雜的數(shù)據結構,其中一個節(jié)點除了含有自身信息外,還應該含有下連接一下個節(jié)點和上一個節(jié)點的信息。

雙向鏈表適用于需要雙向查找節(jié)點值的場景中,在數(shù)據量難以估計并且數(shù)據增刪操作頻繁的場景中,雙向鏈表有一定優(yōu)勢;鏈表在內存中呈現(xiàn)的狀態(tài)是離散的地址塊,不需要像列表一樣預先分配內存空間,在內存的充分利用上更勝一籌,不過增加了一些額外開銷。

雙向鏈表結構如圖:

image

定義基本的節(jié)點類和鏈表類:

class Node:
    """節(jié)點類"""
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None

class DLinkList:
    """
    雙向列表類
    """
    def __init__(self):
        self.head = None

時間雙向鏈表類的基本屬性:是否為空,鏈表長度、鏈表遍歷;判斷鏈表是否為空只需要看頭部head是否指向空,鏈表遍歷只需要從頭部到最后一個節(jié)點的下一個節(jié)點指向為空的情況,同時鏈表長度也是根據最后一個節(jié)點的下一個節(jié)點是否指向空來判斷,基本實現(xiàn)如下:

class Node:
    """節(jié)點類"""
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None

class DLinkList:
    """
    雙向列表類
    """
    def __init__(self):
        self._head = None

    @property
    def is_empty(self):
        return None == self._head

    @property
    def length(self):
        if self.is_empty:
            return 0
        n = 1
        cur = self._head
        while None != cur.next:
            cur = cur.next
            n += 1
        return n

    @property
    def ergodic(self):
        if self.is_empty:
            raise ValueError('ERROR NULL')
        cur = self._head
        print(cur.item)
        while None != cur.next:
            cur = cur.next
            print(cur.item)
        return True

接下來實現(xiàn)添加節(jié)點相關的操作,在頭部添加、任意位置添加、尾部添加,注意在任意插入節(jié)點的時候,需要對節(jié)點進行遍歷并計數(shù),注意計數(shù)起始是1,而不是0,對應的節(jié)點是從第二個節(jié)點開始。

class Node:
    """節(jié)點類"""
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None

class DLinkList:
    """
    雙向列表類
    """
    def __init__(self):
        self._head = None

    @property
    def is_empty(self):
        """
        是否為空
        :return:
        """
        return None == self._head

    @property
    def length(self):
        """
        鏈表長度
        :return:
        """
        if self.is_empty:
            return 0
        n = 1
        cur = self._head
        while None != cur.next:
            cur = cur.next
            n += 1
        return n

    @property
    def ergodic(self):
        """
        遍歷鏈表
        :return:
        """
        if self.is_empty:
            raise ValueError('ERROR NULL')
        cur = self._head
        print(cur.item)
        while None != cur.next:
            cur = cur.next
            print(cur.item)
        return True

    def add(self, item):
        """
        在頭部添加節(jié)點
        :param item:
        :return:
        """
        node = Node(item)
        if self.is_empty:
            self._head = node
        else:
            node.next = self._head
            self._head.prev = node
            self._head = node

    def append(self, item):
        """
        在尾部添加節(jié)點
        :return:
        """
        if self.is_empty:
            self.add(item)
        else:
            node = Node(item)
            cur = self._head
            while None != cur.next:
                cur = cur.next
            cur.next = node
            node.prev = cur

    def insert(self, index, item):
        """
        在任意位置插入節(jié)點
        :param index:
        :param item:
        :return:
        """
        if index == 0:
            self.add(item)
        elif index+1 >= self.length:
            self.append(item)
        else:
            n = 1
            node = Node(item)
            cur = self._head
            while Node != cur.next:
                pre = cur
                cur = cur.next
                if n == index:
                    break
            pre.next = node
            node.prev = pre
            node.next = cur
            cur.prev = node

在實現(xiàn)較為復雜的刪除節(jié)點操作和判斷節(jié)點是否存在的方法。

class Node:
    """節(jié)點類"""
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None

class DLinkList:
    """
    雙向列表類
    """
    def __init__(self):
        self._head = None

    @property
    def is_empty(self):
        """
        是否為空
        :return:
        """
        return None == self._head

    @property
    def length(self):
        """
        鏈表長度
        :return:
        """
        if self.is_empty:
            return 0
        n = 1
        cur = self._head
        while None != cur.next:
            cur = cur.next
            n += 1
        return n

    @property
    def ergodic(self):
        """
        遍歷鏈表
        :return:
        """
        if self.is_empty:
            raise ValueError('ERROR NULL')
        cur = self._head
        print(cur.item)
        while None != cur.next:
            cur = cur.next
            print(cur.item)
        return True

    def add(self, item):
        """
        在頭部添加節(jié)點
        :param item:
        :return:
        """
        node = Node(item)
        if self.is_empty:
            self._head = node
        else:
            node.next = self._head
            self._head.prev = node
            self._head = node

    def append(self, item):
        """
        在尾部添加節(jié)點
        :return:
        """
        if self.is_empty:
            self.add(item)
        else:
            node = Node(item)
            cur = self._head
            while None != cur.next:
                cur = cur.next
            cur.next = node
            node.prev = cur

    def insert(self, index, item):
        """
        在任意位置插入節(jié)點
        :param index:
        :param item:
        :return:
        """
        if index == 0:
            self.add(item)
        elif index+1 >= self.length:
            self.append(item)
        else:
            n = 1
            node = Node(item)
            cur = self._head
            while Node != cur:
                pre = cur
                cur = cur.next
                if n == index:
                    break
            pre.next = node
            node.prev = pre
            node.next = cur
            cur.prev = node

    def search(self, item):
        """
        查找節(jié)點是否存在
        :param item:
        :return:
        """
        if self.is_empty:
            raise ValueError("ERROR NULL")
        cur = self._head
        while None != cur:
            if cur.item == item:
                return True
            cur = cur.next
        return False

    def deltel(self, item):
        """刪除節(jié)點元素"""
        if self.is_empty:
            raise ValueError('ERROR NULL')
        else:
            cur = self._head
            while None != cur:
                if cur.item == item:
                    if not cur.prev:  # 第一個節(jié)點
                        if None != cur.next:  # 不止一個節(jié)點
                            self._head = cur.next
                            cur.next.prev = None
                        else:  # 只有一個節(jié)點
                            self._head = None
                    else:  # 不是第一個節(jié)點
                        if cur.next == None:  # 最后一個節(jié)點
                            cur.prev.next = None
                        else:  # 中間節(jié)點
                            cur.prev.next = cur.next
                            cur.next.prev = cur.prev
                cur = cur.next

注意在刪除節(jié)點的時候要考慮幾種特殊情況:刪除節(jié)點為第一個節(jié)點,并且鏈表只有一個節(jié)點;刪除節(jié)點為第一個節(jié)點并且鏈表長度大于1;刪除節(jié)點是中間節(jié)點;刪除節(jié)點是最后一個節(jié)點;

image

編輯于 22:23

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內容