python實(shí)現(xiàn)雙向鏈表基本結(jié)構(gòu)及其基本方法

雙向鏈表是在單向鏈表的基礎(chǔ)上更為復(fù)雜的數(shù)據(jù)結(jié)構(gòu)匾浪,其中一個節(jié)點(diǎn)除了含有自身信息外酿雪,還應(yīng)該含有下連接一下個節(jié)點(diǎn)和上一個節(jié)點(diǎn)的信息绒净。

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

雙向鏈表結(jié)構(gòu)如圖:

image

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

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

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

時間雙向鏈表類的基本屬性:是否為空售碳,鏈表長度、鏈表遍歷绞呈;判斷鏈表是否為空只需要看頭部head是否指向空贸人,鏈表遍歷只需要從頭部到最后一個節(jié)點(diǎn)的下一個節(jié)點(diǎn)指向?yàn)榭盏那闆r,同時鏈表長度也是根據(jù)最后一個節(jié)點(diǎn)的下一個節(jié)點(diǎn)是否指向空來判斷佃声,基本實(shí)現(xiàn)如下:

class Node:
    """節(jié)點(diǎn)類"""
    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

接下來實(shí)現(xiàn)添加節(jié)點(diǎn)相關(guān)的操作艺智,在頭部添加、任意位置添加圾亏、尾部添加十拣,注意在任意插入節(jié)點(diǎn)的時候,需要對節(jié)點(diǎn)進(jìn)行遍歷并計數(shù)志鹃,注意計數(shù)起始是1夭问,而不是0,對應(yīng)的節(jié)點(diǎn)是從第二個節(jié)點(diǎn)開始曹铃。

class Node:
    """節(jié)點(diǎn)類"""
    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é)點(diǎn)
        :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é)點(diǎn)
        :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é)點(diǎn)
        :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

在實(shí)現(xiàn)較為復(fù)雜的刪除節(jié)點(diǎn)操作和判斷節(jié)點(diǎn)是否存在的方法缰趋。

class Node:
    """節(jié)點(diǎn)類"""
    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é)點(diǎn)
        :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é)點(diǎn)
        :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é)點(diǎn)
        :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é)點(diǎn)是否存在
        :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é)點(diǎn)元素"""
        if self.is_empty:
            raise ValueError('ERROR NULL')
        else:
            cur = self._head
            while None != cur:
                if cur.item == item:
                    if not cur.prev:  # 第一個節(jié)點(diǎn)
                        if None != cur.next:  # 不止一個節(jié)點(diǎn)
                            self._head = cur.next
                            cur.next.prev = None
                        else:  # 只有一個節(jié)點(diǎn)
                            self._head = None
                    else:  # 不是第一個節(jié)點(diǎn)
                        if cur.next == None:  # 最后一個節(jié)點(diǎn)
                            cur.prev.next = None
                        else:  # 中間節(jié)點(diǎn)
                            cur.prev.next = cur.next
                            cur.next.prev = cur.prev
                cur = cur.next

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

image

編輯于 22:23

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末直撤,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蜕着,更是在濱河造成了極大的恐慌谋竖,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件承匣,死亡現(xiàn)場離奇詭異蓖乘,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)韧骗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門嘉抒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人袍暴,你說我怎么就攤上這事些侍×ブⅲ” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵岗宣,是天一觀的道長蚂会。 經(jīng)常有香客問我,道長耗式,這世上最難降的妖魔是什么胁住? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任并鸵,我火速辦了婚禮揭蜒,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘沉删。我一直安慰自己娱挨,他們只是感情好余指,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著让蕾,像睡著了一般浪规。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上探孝,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天,我揣著相機(jī)與錄音誉裆,去河邊找鬼顿颅。 笑死,一個胖子當(dāng)著我的面吹牛足丢,可吹牛的內(nèi)容都是我干的粱腻。 我是一名探鬼主播,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼斩跌,長吁一口氣:“原來是場噩夢啊……” “哼绍些!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起耀鸦,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤柬批,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后袖订,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體氮帐,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年洛姑,在試婚紗的時候發(fā)現(xiàn)自己被綠了上沐。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡楞艾,死狀恐怖参咙,靈堂內(nèi)的尸體忽然破棺而出龄广,到底是詐尸還是另有隱情,我是刑警寧澤蕴侧,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布蜀细,位于F島的核電站,受9級特大地震影響戈盈,放射性物質(zhì)發(fā)生泄漏奠衔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一塘娶、第九天 我趴在偏房一處隱蔽的房頂上張望归斤。 院中可真熱鬧,春花似錦刁岸、人聲如沸脏里。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽迫横。三九已至,卻和暖如春酝碳,著一層夾襖步出監(jiān)牢的瞬間矾踱,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工疏哗, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留呛讲,地道東北人。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓返奉,卻偏偏與公主長得像贝搁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子芽偏,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容