數(shù)據(jù)結(jié)構(gòu)學(xué)習(xí)--單鏈表(python)

概念

鏈表(linked_list)是物理存儲單元上非連續(xù)的颖医、非順序的存儲結(jié)構(gòu)量没,數(shù)據(jù)元素的邏輯順序
是通過鏈表的指針地址實現(xiàn)丑罪,每個元素包含兩個結(jié)點芍耘,一個是存儲元素的數(shù)據(jù)域 (內(nèi)存空間)
,另一個是指向下一個結(jié)點地址的指針域戴涝。根據(jù)指針的指向滋戳,鏈表能形成不同的結(jié)構(gòu)钻蔑,例如
單鏈表,雙向鏈表胧瓜,循環(huán)鏈表等.
鏈表通過將鏈點 i 與其鄰居鏈點 i+1 通過指針相關(guān)聯(lián),從索引 0 到索引 N-1 對鏈點進
行排序.

實現(xiàn)

class Node:
    """
    鏈點
    """

    def __init__(self, data):
        self.data = data    # 數(shù)據(jù)域
        self.next = None    # 指針域


class SingleLinkedList:
    """
    單鏈表
    """

    def __init__(self, head=None):
        self.head = Node(head)    # 鏈表頭部元素
        self._length = None

    # 向鏈表中添加新鏈點
    def append(self, value):
        self._length = None
        new_node = Node(value)
        # 將頭部節(jié)點指向臨時變量
        current = self.head
        # 當(dāng)頭部節(jié)點存在時
        if self.head:
            # 循環(huán)遍歷到鏈表的最后一個節(jié)點
            while current.next:
                current = current.next
            current.next = new_node
        # 當(dāng)頭部節(jié)點不存在時
        else:
            self.head = new_node

    # 判斷鏈表是否為空
    def is_empty(self):
        return bool(self.head)

    # 向鏈表任意位置插入元素
    def insert(self, position, value):
        self._length = None
        new_node = Node(value)
        # 判斷插入位置是否在鏈表的索引范圍內(nèi)
        if position < 0 or position > self.get_length():
            raise IndexError('Out of linked list range.')

        # 當(dāng)插入位置為頭節(jié)點時
        if position == 0:
            new_node.next, self.head = self.head, new_node
            return
        # 當(dāng)插入位置不在頭節(jié)點時,遍歷鏈表找到插入位置,插入新節(jié)點
        current = self.head
        i = 0
        while i < position:
            pre, current = current, current.next
            i += 1
        pre.next, new_node.next = new_node, current

    # 刪除指定位置的節(jié)點
    def remove(self, position):
        self._length = None
        # 判斷刪除位置是否在鏈表的索引范圍內(nèi)
        if position < 0 or position > self.get_length() - 1:
            raise IndexError('Position out of linked list range.')

        i = 0
        current = self.head
        # 當(dāng)刪除位置為頭節(jié)點時
        if position == i:
            self.head, current.next = self.head.next, None
            return

        # 當(dāng)刪除位置不是頭節(jié)點時,遍歷鏈表找到刪除位置
        i += 1
        prev, current = current, current.next
        while i != position:
            prev, current = current, current.next
            i += 1
        prev.next, current.next = current.next, None

    # 獲取鏈表長度
    def get_length(self):
        if self._length is not None:
            return self._length
        current = self.head
        length = 0
        while current is not None:
            length += 1
            current = current.next
        self._length = length
        return length

    # 遍歷鏈表,并依次打印節(jié)點數(shù)據(jù)
    def print_list(self):
        print('linked_list:')
        current = self.head
        while current is not None:
            print(current.data)
            current = current.next

    # 將鏈表反轉(zhuǎn)
    def reverse(self):
        prev = None
        current = self.head
        while current is not None:
            # next_node = current.next
            # current.next = prev
            # prev = current
            # current = next_node
            next_node, current.next = current.next, prev
            prev, current = current, next_node
        self.head = prev

    # 將列表轉(zhuǎn)換為鏈表
    def init_list(self, data_list):
        self.head = Node(data_list[0])
        current = self.head
        for item in data_list[1:]:
            node = Node(item)
            current.next, current = node, node

    # 替換指定位置的節(jié)點
    def replace(self, position, value):
        # 判斷替換位置是否在鏈表索引范圍內(nèi)
        if position < 0 or position > self.get_length() - 1:
            raise IndexError("Position out of linked-list range.")
        _node = Node(value)
        _current = self.head
        i = 0
        if position == 0:
            _node.next, self.head = self.head.next, _node
            _current.next = None
        else:
            i += 1
            _prev, _current = _current, _current.next
            while i != position:
                i += 1
                _prev, _current = _current, _current.next
            _prev.next, _node.next = _node, _current.next
            _current.next = None

    # 返回給定值的第一個節(jié)點索引
    def index(self, value):
        _current = self.head
        i = 0
        while _current is not None:
            if _current.data == value:
                return i
            i += 1
            _current = _current.next
        return -1

    def __getitem__(self, position):
        if position < 0 or position > self.get_length() - 1:
            raise IndexError("Position out of linked-list range.")
        _current = self.head
        i = 0
        while i != position:
            _current = _current.next
            i += 1
        return _current.data
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末郑什,一起剝皮案震驚了整個濱河市府喳,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蘑拯,老刑警劉巖钝满,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異申窘,居然都是意外死亡弯蚜,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門剃法,熙熙樓的掌柜王于貴愁眉苦臉地迎上來碎捺,“玉大人,你說我怎么就攤上這事贷洲∈粘” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵优构,是天一觀的道長诵叁。 經(jīng)常有香客問我,道長钦椭,這世上最難降的妖魔是什么拧额? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮彪腔,結(jié)果婚禮上侥锦,老公的妹妹穿的比我還像新娘。我一直安慰自己德挣,他們只是感情好捎拯,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著盲厌,像睡著了一般署照。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上吗浩,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天建芙,我揣著相機與錄音,去河邊找鬼懂扼。 笑死禁荸,一個胖子當(dāng)著我的面吹牛右蒲,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播赶熟,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼瑰妄,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了映砖?” 一聲冷哼從身側(cè)響起间坐,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎邑退,沒想到半個月后竹宋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡地技,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年蜈七,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片莫矗。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡飒硅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出作谚,到底是詐尸還是另有隱情狡相,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布食磕,位于F島的核電站尽棕,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏彬伦。R本人自食惡果不足惜滔悉,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望单绑。 院中可真熱鬧回官,春花似錦、人聲如沸搂橙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽区转。三九已至苔巨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間废离,已是汗流浹背侄泽。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蜻韭,地道東北人悼尾。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓柿扣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親闺魏。 傳聞我的和親對象是個殘疾皇子未状,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354