鏈表

概念
鏈表(linked list)是一種常見的線性表結(jié)構(gòu)癌幕,在存儲(chǔ)單元上非連續(xù)拒名,非順序的存儲(chǔ)結(jié)構(gòu)中燥,由節(jié)點(diǎn)組成羽戒,節(jié)點(diǎn)可以在運(yùn)行中動(dòng)態(tài)生成缤沦,每一個(gè)節(jié)點(diǎn)中存放兩種信息:當(dāng)前節(jié)點(diǎn)的數(shù)據(jù)域,下一個(gè)節(jié)點(diǎn)的位置信息(指針域)易稠,需要說(shuō)明的是python中鏈表和棧都是自定義的數(shù)據(jù)結(jié)構(gòu)(需要自己定義實(shí)現(xiàn))

image.png

  • head:頭結(jié)點(diǎn)
  • val:當(dāng)前節(jié)點(diǎn)的數(shù)據(jù)
  • next:下一個(gè)節(jié)點(diǎn)的存放位置
  • last:尾結(jié)點(diǎn)缸废,一般用tail表示

單向鏈表的實(shí)現(xiàn):鏈表的頭插,尾插驶社,指定位置插入企量,頭刪,刪除指定元素亡电,獲取鏈表長(zhǎng)度届巩,打印鏈表所有元素,查找鏈表中指定元素

"""
鏈表:
"""
class ListNode(object):
    def __init__(self, val, next):
        self.val = val
        self.next = next


class LinkedList(object):

    def __init__(self):
        self.head = None
        
    #鏈表的頭插
    def Headinsert(self, elem):
        cur = ListNode(elem, None)
        cur.next = self.head
        self.head = cur

    #鏈表的尾插
    def append(self, elem):
        if self.head == None:
            self.Headinsert(elem)

        else:
            cur = self.head

            while cur.next != None:
                cur = cur.next

            node = ListNode(elem, None)
            cur.next = node

    #指定位置插入元素
    def insert(self, pos, val):
        if pos <= 0:
            self.Headinsert(val)

        elif pos > self.len():
            self.append(val)

        else:
            count = 0
            cur = self.head
            while count < pos - 1:
                cur = cur.next
                count += 1

            node = ListNode(val, None)
            tail = cur.next
            cur.next = node
            node.next = tail

    #鏈表的頭刪
    def Pophead(self):
        if self.head == None:
            return None
        else:
            cur = self.head.next

            elem = self.head.val
            self.head = None

            self.head = cur
            return elem

    #刪除鏈表的指定元素
    def remove(self, val):
        if val == self.head.val:
            self.Pophead()
        else:
            cur = self.head
            #找到要?jiǎng)h除元素的前一個(gè)節(jié)點(diǎn)
            while cur.next.val != val:
                cur = cur.next

            cur.next = cur.next.next

    #查找節(jié)點(diǎn)
    def search(self, val):
        if self.head == None:
            return False

        cur = self.head
        while cur != None:
            if cur.val == val:
                return True
            else:
                cur = cur.next
        return False

    #遍歷鏈表
    def traval(self):
        if self.head == None:
            return None

        cur = self.head
        while cur != None:
            print(cur.val)
            cur = cur.next

    #獲取鏈表長(zhǎng)度
    def len(self):
        if self.head == None:
            return 0

        cur = self.head
        count = 0
        while cur != None:
            count += 1
            cur = cur.next

        return count

if __name__ == '__main__':
    lk = LinkedList()
    # print(lk.len())

    # lk.Headinsert(4)
    # lk.Headinsert(5)
    lk.Headinsert(6)
    lk.insert(2, 3)
    # lk.Headinsert(5)
    # lk.append(10)
    # lk.Pophead()
    # lk.remove(6)
    # lk.traval()
    # print(lk.search(19))
    print(lk.len())

單向循環(huán)鏈表:與單向鏈表的區(qū)別是:?jiǎn)蜗蜓h(huán)鏈表的尾節(jié)點(diǎn)指向頭結(jié)點(diǎn)

#創(chuàng)建節(jié)點(diǎn)
class ListNode(object):

    #初始化節(jié)點(diǎn)的元素
    def __init__(self, val):
        self.val = val
        self.next = None


#創(chuàng)建鏈表類
class LinkList(object):

    def __init__(self):
        self.head = None
        self.tail = None

    #獲取鏈表的長(zhǎng)度
    def len(self):
        if self.head == None:
            return 0
        else:

            cur = self.head
            count = 0
            while cur.next != self.head:

                cur = cur.next
                count += 1

            return count + 1


    #頭插
    def insertHead(self, val):
        node = ListNode(val)
        if self.head == None:
            self.head = node
            node.next = self.head

        else:
            cur = self.head
            while cur.next != self.head:
                cur = cur.next

            cur.next = node
            node.next = self.head
            self.head = node

    #尾插
    def append(self, data):
        node = ListNode(data)

        if self.head == None:
           self.head = node
           node.next = self.head

        else:
            node.next = self.head
            cur = self.head

            while cur.next != self.head:
                cur = cur.next

            cur.next = node

    #指定位置插入
    def insert(self, pos, val):
        node = ListNode(val)
        if pos <= 0:
            self.head = node
            node.next = self.head

        elif pos > self.len():
            self.append(val)
        else:
            cur = self.head
            count = 0
            while count < pos - 1:
                cur = cur.next
                count += 1

            tail = cur.next
            cur.next = node
            node.next = tail


    #頭刪
    def pop(self):
        if self.head == None:
            return None
        else:
            if self.len() <= 1:
                ele = self.head.val
                self.head = None
                return ele
            else:
                cur = self.head
                ele = self.head.val
                while cur.next != self.head:
                    cur = cur.next

                new_head = self.head.next
                self.head = new_head
                cur.next = new_head
                return ele

    #尾刪
    def tailDel(self):
        if self.head == None:
            return None
        else:
            if self.len() <= 1:
                ele = self.head.val
                self.head = None
                return ele
            else:
                cur = self.head
                count = 1
                while count < self.len() - 1:
                    cur = cur.next
                    count += 1

                ele = cur.next.val
                cur.next = self.head
                return ele



    #刪除指定位置元素
    def remove(self, pos):
        if self.head == None:
            return None
        else:
            if pos <= 0:
                self.pop()
            elif pos >= self.len():
                self.tailDel()
            else:
                cur = self.head
                count = 0
                while count < pos - 1 :
                    cur = cur.next
                    count += 1

                ele = cur.next.val
                cur.next = cur.next.next
                return ele

    # 打印鏈表
    def traval(self):
        res = []
        if self.head == None:
            return res

        cur = self.head
        res.append(cur.val)
        while cur.next != self.head:
            cur = cur.next
            res.append(cur.val)

        return res

if __name__ == '__main__':
    lk = LinkList()
    lk.insertHead(3)
    # lk.insertHead(4)
    # lk.insert(2, 10)
    lk.append(4)
    lk.insertHead(10)

    # lk.tailDel()
    # print(lk.pop())
    # lk.remove()
    lk.remove(1)
    print(lk.traval())

    print(lk.len())

雙向鏈表:有兩個(gè)指針份乒,一個(gè)指向next恕汇,一個(gè)指向pre

"""
雙向鏈表
"""
class ListNode():
    def __init__(self, val):
        self.next = None
        self.pre = None
        self.val = val

class DoubleLinkList():
    def __init__(self):
        self.head = None
        self.length = 0
    #頭插
    def insert(self, val):
        node = ListNode(val)

        if self.head == None:
            self.head = node
        else:
            node.next = self.head
            self.head.pre = node
            self.head = node

        self.length += 1

    #尾插
    def append(self, val):
        node = ListNode(val)
        if self.head == None:
            self.head = node
        else:
            cur = self.head
            while cur.next != None:
                cur = cur.next

            node = ListNode(val)
            cur.next = node
            node.pre = cur

        self.length += 1

    #指定位置插入
    def insertIndex(self, pos, val):

        if pos <= 0:
            self.insert(val)
        elif pos >= self.length:
            self.append(val)
        else:
            count = 0
            cur = self.head
            while count < pos - 1:
                cur = cur.next
                count += 1

            node = ListNode(val)
            node.next = cur.next
            cur.next.pre = node

            node.pre = cur
            cur.next = node

        self.length += 1

    #頭刪
    def pop(self):
        if self.head == None:
            return None
        else:
            cur = self.head
            ele = cur.val

            self.head = cur.next
            self.head.pre = None

            self.length -=1
            return ele

    #尾刪
    def remove(self):
        if self.head == None:
            return None
        else:
            cur = self.head
            while cur.next != None:
                cur = cur.next

            ele = cur.val
            cur.pre.next = None

            self.length -= 1
            return ele

    #指定位置刪除
    def popIndex(self, pos):
        if pos <= 0:
            self.pop()
        elif pos >= self.length:
            self.remove()
        else:
            count = 0
            cur = self.head
            while count < pos:
                cur = cur.next
                count += 1

            ele = cur.val

            cur.next.pre = cur.pre
            cur.pre.next = cur.next
            self.length -= 1
            return ele

    #遍歷鏈表
    def traval(self):
        res = []
        if self.head == None:
            return res
        else:
            cur = self.head
            while cur != None:
                res.append(cur.val)
                cur = cur.next

            return res



if __name__ == '__main__':
    lk = DoubleLinkList()
    # lk.insert(3)
    # lk.insert(4)
    lk.insert(5)

    lk.append(10)
    lk.insertIndex(1, 20)
    # lk.pop()
    # lk.remove()
    # lk.pop()
    lk.popIndex(0)
    print(lk.traval())
    print(lk.length)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市或辖,隨后出現(xiàn)的幾起案子瘾英,更是在濱河造成了極大的恐慌,老刑警劉巖孝凌,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件方咆,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡蟀架,警方通過(guò)查閱死者的電腦和手機(jī)瓣赂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門榆骚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人煌集,你說(shuō)我怎么就攤上這事妓肢。” “怎么了苫纤?”我有些...
    開封第一講書人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵碉钠,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我卷拘,道長(zhǎng)喊废,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任栗弟,我火速辦了婚禮污筷,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘乍赫。我一直安慰自己瓣蛀,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開白布雷厂。 她就那樣靜靜地躺著惋增,像睡著了一般。 火紅的嫁衣襯著肌膚如雪改鲫。 梳的紋絲不亂的頭發(fā)上诈皿,一...
    開封第一講書人閱讀 51,763評(píng)論 1 307
  • 那天,我揣著相機(jī)與錄音钩杰,去河邊找鬼纫塌。 笑死,一個(gè)胖子當(dāng)著我的面吹牛讲弄,可吹牛的內(nèi)容都是我干的措左。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼避除,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼怎披!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起瓶摆,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤凉逛,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后群井,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體状飞,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了诬辈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片酵使。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖焙糟,靈堂內(nèi)的尸體忽然破棺而出口渔,到底是詐尸還是另有隱情,我是刑警寧澤穿撮,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布缺脉,位于F島的核電站,受9級(jí)特大地震影響悦穿,放射性物質(zhì)發(fā)生泄漏攻礼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一咧党、第九天 我趴在偏房一處隱蔽的房頂上張望秘蛔。 院中可真熱鬧,春花似錦傍衡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至遮糖,卻和暖如春绣的,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背欲账。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工屡江, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人赛不。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓惩嘉,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親踢故。 傳聞我的和親對(duì)象是個(gè)殘疾皇子文黎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

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