基礎(chǔ)篇(3)LeetCode--CHAPTER 2. LINKED LIST

Unit 1 Practice I

237. Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

//Definition for singly-linked list.
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
 
public class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

圖示如下:

  • Delete Node in Linked List

Unit 2 Practice II

206. Reverse Linked List

Reverse a singly linked list.

Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?

(1) Reverse the linked list iteratively

  • reverseLinkedlist.jpg
// Definition for singly-linked list.
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public ListNode reverseList(ListNode head) {
    if (head == null ||head.next == null) {
        return head;
    }
    ListNode pre = head;
    ListNode cur = pre.next;
    
    head.next = null;
    
    while (pre != null && cur != null) {
        ListNode temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
    }
    return pre;
}

(2) Reverse the linked list recursively

  • ReverseLinkedlistRecursively.jpg

    舉例說明:反轉(zhuǎn)1->2->3->4
    (i)假設(shè)1->2->3->4已經(jīng)反轉(zhuǎn)好导饲,成為4->3->2->1逃贝,然后將4->3->2->1看成一個整體砸琅,讓這個整體的next指向null变过;
    (ii)假設(shè)2->3->4已經(jīng)反轉(zhuǎn)好涝涤,已經(jīng)成為了4->3->2, 然后將4->3->2看成一個整體媚狰,讓這個整體的next指向1阔拳;
    (iii)接下來問題變成了反轉(zhuǎn)2->3->4
    假設(shè)3->4已經(jīng)反轉(zhuǎn)好,已經(jīng)成為了4->3, 然后將4->3看成一個整體糊肠,讓這個整體的next指向2;
    (iv)然后問題變成了反轉(zhuǎn)3->4
    假設(shè)4(實際上是4->NULL)已經(jīng)反轉(zhuǎn)好货裹,已經(jīng)成為了4(其實是head->4), 然后將4(其實是head->4)看成一個整體,讓這個整體的next指向3泪酱;
    (v)然后問題變成了反轉(zhuǎn)4还最,head->4。

// Definition for singly-linked list.
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

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

Unit 3 Practice III

LeetCode 141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

  1. Use two pointers, slower and faster.
  2. Slower moves step by step. faster moves two steps at the same time.
  3. If the Linked List has a cycle slower and faster will meet at some point.
public boolean hasCycle(ListNode head) {
    if(head == null) {
        return false;
    }
    ListNode slower = head;
    ListNode faster = head;
    while(faster.next != null && faster.next.next!= null) {
        slower = slower.next;
        faster = faster.next.next;
        if (slower == faster) {
            return true;
        }
    }
    return false;
}

Unit 4 Practice IV

LeetCode 21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

  1. The key to solve the problem is defining a fake head.
  2. Then compare the first elements from each list.
  3. Add the smaller one to the merged list.
  4. Finally, when one of them is empty, simply append it to the merged list, since it is already sorted.
class ListNode {
    int val; 
    ListNode next;
    ListNode (int x) {
        val = x;
    }
    public static ListNode mergeTwoListNode (ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode result = head;
        while (l1 != null || l2 != null) {
            if (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    result.next = l1;
                    l1 = l1.next;
                }
                else{
                    result.next = l2;
                    l2 = l2.next;
                }
                result = result.next;
            }
            else if (l1 == null) {
                result.next = l2;
                break;
            }
            else if (l2 == null) {
                result.next = l1;
                break;
            }
        }
        return head.next;
    }
    public static void main (String args[]) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(3);
        l1.next.next = new ListNode(5);
        l1.next.next.next = new ListNode(7);

        ListNode l2 = new ListNode(2);
        l2.next = new ListNode(4);
        l2.next.next = new ListNode(6);
        l2.next.next.next = new ListNode(8);        

        ListNode result = mergeTwoListNode(l1, l2);
        while (result != null) {
            System.out.print (result.val + " ");
            result = result.next;
        }
        System.out.println();
    }
}

Unit 5 Practice V

LeetCode 24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. (意思就是不允許換值)

  • SwapNodesInPairs.jpg
class ListNode {
    int val; 
    ListNode next;
    ListNode (int x) {
        val = x;
    }
    public static ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode node = dummy;
        
        while(head != null && head.next != null){
            node.next = head.next;
            head.next = node.next.next;
            node.next.next = head;
            node = head;
            head = head.next;
        }
        return dummy.next;
    }

    public static void main (String args[]) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);


        ListNode result = swapPairs(head);
        while (result != null) {
            System.out.print (result.val + " ");
            result = result.next;
        }
        System.out.println();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末扶叉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子枣氧,更是在濱河造成了極大的恐慌,老刑警劉巖张弛,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異吞鸭,居然都是意外死亡,警方通過查閱死者的電腦和手機刻剥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來御吞,“玉大人,你說我怎么就攤上這事魄藕。” “怎么了背率?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵嫩与,是天一觀的道長寝姿。 經(jīng)常有香客問我划滋,道長,這世上最難降的妖魔是什么处坪? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮玄帕,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘想邦。我一直安慰自己,他們只是感情好丧没,可當我...
    茶點故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著漆际,像睡著了一般。 火紅的嫁衣襯著肌膚如雪灿椅。 梳的紋絲不亂的頭發(fā)上套蒂,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天茫蛹,我揣著相機與錄音,去河邊找鬼婴洼。 笑死,一個胖子當著我的面吹牛柬采,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播粉捻,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼祟霍!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起盈包,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎崭添,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體呼渣,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡寞埠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了畸裳。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,703評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡怖糊,死狀恐怖颇象,靈堂內(nèi)的尸體忽然破棺而出伍伤,到底是詐尸還是另有隱情遣钳,我是刑警寧澤,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站姐直,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蒋畜。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一姻成、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧均牢,春花似錦、人聲如沸徘跪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽乎澄。三九已至,卻和暖如春置济,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背浙于。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留腐宋,地道東北人。 一個月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓胸竞,卻偏偏與公主長得像参萄,于是被迫代替她去往敵國和親卫枝。 傳聞我的和親對象是個殘疾皇子讹挎,可洞房花燭夜當晚...
    茶點故事閱讀 44,601評論 2 353

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