[leetcode707] 設(shè)計(jì)鏈表(medium)

題目

設(shè)計(jì)鏈表的實(shí)現(xiàn)沥匈。您可以選擇使用單鏈表或雙鏈表而芥。單鏈表中的節(jié)點(diǎn)應(yīng)該具有兩個(gè)屬性:val 和 next。val 是當(dāng)前節(jié)點(diǎn)的值缓待,next 是指向下一個(gè)節(jié)點(diǎn)的指針/引用。如果要使用雙向鏈表渠牲,則還需要一個(gè)屬性 prev 以指示鏈表中的上一個(gè)節(jié)點(diǎn)旋炒。假設(shè)鏈表中的所有節(jié)點(diǎn)都是 0-index 的。

在鏈表類中實(shí)現(xiàn)這些功能:
get(index):獲取鏈表中第 index 個(gè)節(jié)點(diǎn)的值签杈。如果索引無效瘫镇,則返回-1。
addAtHead(val):在鏈表的第一個(gè)元素之前添加一個(gè)值為 val 的節(jié)點(diǎn)答姥。插入后铣除,新節(jié)點(diǎn)將成為鏈表的第一個(gè)節(jié)點(diǎn)。
addAtTail(val):將值為 val 的節(jié)點(diǎn)追加到鏈表的最后一個(gè)元素鹦付。
addAtIndex(index,val):在鏈表中的第 index 個(gè)節(jié)點(diǎn)之前添加值為 val 的節(jié)點(diǎn)通孽。如果 index 等于鏈表的長度,則該節(jié)點(diǎn)將附加到鏈表的末尾睁壁。如果 index 大于鏈表長度背苦,則不會插入節(jié)點(diǎn)。如果index小于0潘明,則在頭部插入節(jié)點(diǎn)行剂。
deleteAtIndex(index):如果索引 index 有效,則刪除鏈表中的第 index 個(gè)節(jié)點(diǎn)钳降。

示例

MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2);  //鏈表變?yōu)?-> 2-> 3
linkedList.get(1);            //返回2
linkedList.deleteAtIndex(1);  //現(xiàn)在鏈表是1-> 3
linkedList.get(1);            //返回3

提示:

所有val值都在 [1, 1000] 之內(nèi)厚宰。
操作次數(shù)將在 [1, 1000] 之內(nèi)。
請不要使用內(nèi)置的 LinkedList 庫遂填。

題解

使用單鏈表

class MyLinkedList {

    int size;
    ListNode head;
    /** Initialize your data structure here. */
    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    public int get(int index) {
        if(index<0 || index>= size)
            return -1;
        ListNode curr = head;
        for(int i=0;i<index+1;i++) curr = curr.next;
        return curr.val;
    }
    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    public void addAtHead(int val) {
        addAtIndex(0,val);
    }
    /** Append a node of value val to the last element of the linked list. */
    public void addAtTail(int val) {
        addAtIndex(size,val);
    }
    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    public void addAtIndex(int index, int val) {
        if(index>size) return;
        if(index<0) index=0;
        ++size;
        ListNode pred = head;
        for(int i=0;i<index;i++) pred = pred.next;
        ListNode toAdd = new ListNode(val);
        toAdd.next = pred.next;
        pred.next = toAdd;
    }
    
    /** Delete the index-th node in the linked list, if the index is valid. */
    public void deleteAtIndex(int index) {
        if(index<0 || index >= size) return;

        size--;
        ListNode pred = head;
        for(int i=0;i<index;i++) pred = pred.next;
        pred.next = pred.next.next;
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */

復(fù)雜度分析

時(shí)間復(fù)雜度:

  • addAtHead: \mathcal{O}(1)O(1)
  • addAtInder铲觉,get,deleteAtIndex: \mathcal{O}(k)O(k)吓坚,其中 kk 指的是元素的索引撵幽。
  • addAtTail:\mathcal{O}(N)O(N),其中 NN 指的是鏈表的元素個(gè)數(shù)礁击。

空間復(fù)雜度:所有的操作都是 O(1)O(1)盐杂。

使用雙鏈表

public class ListNode {
  int val;
  ListNode next;
  ListNode prev;
  ListNode(int x) { val = x; }
}
class MyLinkedList {
  int size;
  // sentinel nodes as pseudo-head and pseudo-tail
  ListNode head, tail;
  public MyLinkedList() {
    size = 0;
    head = new ListNode(0);
    tail = new ListNode(0);
    head.next = tail;
    tail.prev = head;
  }
  /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
  public int get(int index) {
    // if index is invalid
    if (index < 0 || index >= size) return -1;

    // choose the fastest way: to move from the head
    // or to move from the tail
    ListNode curr = head;
    if (index + 1 < size - index)
      for(int i = 0; i < index + 1; ++i) curr = curr.next;
    else {
      curr = tail;
      for(int i = 0; i < size - index; ++i) curr = curr.prev;
    }
    return curr.val;
  }
  /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
  public void addAtHead(int val) {
    ListNode pred = head, succ = head.next;
    ++size;
    ListNode toAdd = new ListNode(val);
    toAdd.prev = pred;
    toAdd.next = succ;
    pred.next = toAdd;
    succ.prev = toAdd;
  }
  /** Append a node of value val to the last element of the linked list. */
  public void addAtTail(int val) {
    ListNode succ = tail, pred = tail.prev;
    ++size;
    ListNode toAdd = new ListNode(val);
    toAdd.prev = pred;
    toAdd.next = succ;
    pred.next = toAdd;
    succ.prev = toAdd;
  }
  /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
  public void addAtIndex(int index, int val) {
    // If index is greater than the length, 
    // the node will not be inserted.
    if (index > size) return;
    // [so weird] If index is negative, 
    // the node will be inserted at the head of the list.
    if (index < 0) index = 0;

    // find predecessor and successor of the node to be added
    ListNode pred, succ;
    if (index < size - index) {
      pred = head;
      for(int i = 0; i < index; ++i) pred = pred.next;
      succ = pred.next;
    }
    else {
      succ = tail;
      for (int i = 0; i < size - index; ++i) succ = succ.prev;
      pred = succ.prev;
    }
    // insertion itself
    ++size;
    ListNode toAdd = new ListNode(val);
    toAdd.prev = pred;
    toAdd.next = succ;
    pred.next = toAdd;
    succ.prev = toAdd;
  }
  /** Delete the index-th node in the linked list, if the index is valid. */
  public void deleteAtIndex(int index) {
    // if the index is invalid, do nothing
    if (index < 0 || index >= size) return;

    // find predecessor and successor of the node to be deleted
    ListNode pred, succ;
    if (index < size - index) {
      pred = head;
      for(int i = 0; i < index; ++i) pred = pred.next;
      succ = pred.next.next;
    }
    else {
      succ = tail;
      for (int i = 0; i < size - index - 1; ++i) succ = succ.prev;
      pred = succ.prev.prev;
    }
    // delete pred.next 
    --size;
    pred.next = succ;
    succ.prev = pred;
  }
}

復(fù)雜度分析

時(shí)間復(fù)雜度:

  • addAtHead,addAtTail: \mathcal{O}(1)O(1)
  • get哆窿,addAtIndex链烈,delete:\mathcal{O}(\min(k, N - k))O(min(k,N?k)),其中 kk 指的是元素的索引挚躯。

空間復(fù)雜度:所有的操作都是 \mathcal{O}(1)O(1)强衡。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市码荔,隨后出現(xiàn)的幾起案子漩勤,更是在濱河造成了極大的恐慌号涯,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,000評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件锯七,死亡現(xiàn)場離奇詭異链快,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)眉尸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評論 3 399
  • 文/潘曉璐 我一進(jìn)店門域蜗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人噪猾,你說我怎么就攤上這事霉祸。” “怎么了袱蜡?”我有些...
    開封第一講書人閱讀 168,561評論 0 360
  • 文/不壞的土叔 我叫張陵丝蹭,是天一觀的道長。 經(jīng)常有香客問我坪蚁,道長奔穿,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,782評論 1 298
  • 正文 為了忘掉前任敏晤,我火速辦了婚禮贱田,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘嘴脾。我一直安慰自己男摧,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評論 6 397
  • 文/花漫 我一把揭開白布译打。 她就那樣靜靜地躺著耗拓,像睡著了一般。 火紅的嫁衣襯著肌膚如雪奏司。 梳的紋絲不亂的頭發(fā)上乔询,一...
    開封第一講書人閱讀 52,394評論 1 310
  • 那天,我揣著相機(jī)與錄音结澄,去河邊找鬼哥谷。 笑死,一個(gè)胖子當(dāng)著我的面吹牛麻献,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播猜扮,決...
    沈念sama閱讀 40,952評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼勉吻,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了旅赢?” 一聲冷哼從身側(cè)響起齿桃,我...
    開封第一講書人閱讀 39,852評論 0 276
  • 序言:老撾萬榮一對情侶失蹤惑惶,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后短纵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體带污,經(jīng)...
    沈念sama閱讀 46,409評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評論 3 341
  • 正文 我和宋清朗相戀三年香到,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了鱼冀。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,615評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡悠就,死狀恐怖千绪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情梗脾,我是刑警寧澤荸型,帶...
    沈念sama閱讀 36,303評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站炸茧,受9級特大地震影響瑞妇,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜梭冠,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評論 3 334
  • 文/蒙蒙 一踪宠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧妈嘹,春花似錦柳琢、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至毙驯,卻和暖如春倒堕,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背爆价。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評論 1 272
  • 我被黑心中介騙來泰國打工垦巴, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人铭段。 一個(gè)月前我還...
    沈念sama閱讀 49,041評論 3 377
  • 正文 我出身青樓骤宣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親序愚。 傳聞我的和親對象是個(gè)殘疾皇子憔披,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評論 2 359