開發(fā)人員必須掌握的高頻算法題之鏈表(2)

1.移除鏈表元素
刪除鏈表中等于給定值 val 的所有節(jié)點(diǎn)定续。

  public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }


public ListNode removeElements(ListNode head, int val) {
        ListNode dy = new ListNode(-1);
        dy.next = head;
        ListNode curNode = dy;

        while (curNode.next != null) {
            if (curNode.next.val == val) {
                curNode.next = curNode.next.next;
            } else {
                curNode = curNode.next;
            }
        }

        return dy.next;
    }

2.設(shè)計(jì)鏈表
在鏈表類中實(shí)現(xiàn)這些功能:
1. get(index):獲取鏈表中第 index 個(gè)節(jié)點(diǎn)的值捶惜。如果索引無效鸽心,則返回-1瞒滴。
2. addAtHead(val):在鏈表的第一個(gè)元素之前添加一個(gè)值為 val 的節(jié)點(diǎn)姨夹。插入后夸溶,新節(jié)點(diǎn)將成為鏈表的第一個(gè)節(jié)點(diǎn)。
3. addAtTail(val):將值為 val 的節(jié)點(diǎn)追加到鏈表的最后一個(gè)元素剧辐。
4. addAtIndex(index,val):在鏈表中的第 index 個(gè)節(jié)點(diǎn)之前添加值為 val 的節(jié)點(diǎn)寒亥。如果 index 等于鏈表的長度,則該節(jié)點(diǎn)將附加到鏈表的末尾荧关。如果 index 大于鏈表長度溉奕,則不會(huì)插入節(jié)點(diǎn)。如果index小于0忍啤,則在頭部插入節(jié)點(diǎn)加勤。
5. deleteAtIndex(index):如果索引 index 有效,則刪除鏈表中的第 index 個(gè)節(jié)點(diǎn)同波。

 class MyLinkedList {

        ListNode head = null;

        /**
         * Initialize your data structure here.
         */
        public MyLinkedList() {

        }

        /**
         * 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 (head == null) {
                return -1;
            } else {
                ListNode node = head;
                for (int i = 0; i < index; i++) {
                    node = node.next;
                    if (node == null) {
                        return -1;
                    }
                }
                return node.val;
            }
        }

        public ListNode getNode(int index) {
            if (head == null) {
                return head;
            } else {
                ListNode node = head;
                for (int i = 0; i < index; i++) {
                    node = node.next;
                    if (node == null) {
                        return node;
                    }
                }
                return node;
            }
        }

        /**
         * 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) {
            if (head == null) {
                head = new ListNode(val);
            } else {
                ListNode node = new ListNode(val);
                node.next = head;
                head = node;
            }
        }

        /**
         * Append a node of value val to the last element of the linked list.
         */
        public void addAtTail(int val) {
            if (head == null) {
                head = new ListNode(val);
            } else {
                ListNode node = head;
                while (node.next != null) {
                    node = node.next;
                }
                node.next = new ListNode(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 <= 0) {
                addAtHead(val);
            } else {
                ListNode preNode = getNode(index - 1);
                ListNode nextNode = getNode(index);
                ListNode culNode = new ListNode(val);

                preNode.next = culNode;
                culNode.next = nextNode;
            }
        }

        /**
         * Delete the index-th node in the linked list, if the index is valid.
         */
        public void deleteAtIndex(int index) {
            if (index == 0) {
                head = head.next;
            } else {
                ListNode node = getNode(index - 1);
                if (node != null && node.next != null) {
                    node.next = node.next.next;
                }
            }
        }
    }

3.反轉(zhuǎn)鏈表
題意:反轉(zhuǎn)一個(gè)單鏈表鳄梅。
示例: 輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

迭代實(shí)現(xiàn)

  public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }


        ListNode culNode = head;
        ListNode preNode = null;


        while (culNode != null) {
            ListNode nextNode = culNode.next;
            culNode.next = preNode;
            preNode = culNode;
            culNode = nextNode;
        }

        return preNode;
    }

遞歸實(shí)現(xiàn)

 public ListNode reverseList(ListNode head) {
        return reverse(null, head);
    }

    public ListNode reverse(ListNode pre, ListNode cul) {
        if (cul == null) {
            return pre;
        }
        ListNode next = cul.next;
        cul.next = pre;
        return reverse(cul, next);
    }

4.環(huán)形鏈表II
題意:給定一個(gè)鏈表,返回鏈表開始入環(huán)的第一個(gè)節(jié)點(diǎn)未檩。 如果鏈表無環(huán)戴尸,則返回 null。
為了表示給定鏈表中的環(huán)冤狡,使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)孙蒙。
如果 pos 是 -1项棠,則在該鏈表中沒有環(huán)。
「說明」:不允許修改給定的鏈表挎峦。

 //用set
    public ListNode detectCycle(ListNode head) {
        HashSet<ListNode> set = new HashSet();
        while (head != null) {
            if (!set.add(head)) {
                return head;
            }
            head = head.next;
        }
        return null;
    }

    //快慢指針
    public ListNode detectCycle2(ListNode head) {
        ListNode fastIndex = head;
        ListNode slowIndex = head;
        while (fastIndex != null && fastIndex.next != null) {
            fastIndex = fastIndex.next.next;
            slowIndex = slowIndex.next;
            if (fastIndex == slowIndex) {
                fastIndex = head;
                while (fastIndex != slowIndex) {
                    fastIndex = fastIndex.next;
                    slowIndex = slowIndex.next;
                }
                return fastIndex;
            }
        }
        return null;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末香追,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子坦胶,更是在濱河造成了極大的恐慌透典,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件顿苇,死亡現(xiàn)場離奇詭異峭咒,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)岖圈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門讹语,熙熙樓的掌柜王于貴愁眉苦臉地迎上來钙皮,“玉大人蜂科,你說我怎么就攤上這事《烫酰” “怎么了导匣?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長茸时。 經(jīng)常有香客問我贡定,道長,這世上最難降的妖魔是什么可都? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任缓待,我火速辦了婚禮,結(jié)果婚禮上渠牲,老公的妹妹穿的比我還像新娘旋炒。我一直安慰自己,他們只是感情好签杈,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布瘫镇。 她就那樣靜靜地躺著,像睡著了一般答姥。 火紅的嫁衣襯著肌膚如雪铣除。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天鹦付,我揣著相機(jī)與錄音尚粘,去河邊找鬼。 笑死敲长,一個(gè)胖子當(dāng)著我的面吹牛郎嫁,可吹牛的內(nèi)容都是我干的互捌。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼行剂,長吁一口氣:“原來是場噩夢啊……” “哼秕噪!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起厚宰,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤腌巾,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后铲觉,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體澈蝙,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年撵幽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了灯荧。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡盐杂,死狀恐怖逗载,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情链烈,我是刑警寧澤厉斟,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站强衡,受9級(jí)特大地震影響擦秽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜漩勤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一感挥、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧越败,春花似錦触幼、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至噪猾,卻和暖如春霉祸,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背袱蜡。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來泰國打工丝蹭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人坪蚁。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓奔穿,卻偏偏與公主長得像镜沽,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子贱田,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

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