基础篇(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

    举例说明:反转1->2->3->4
    (i)假设1->2->3->4已经反转好,成为4->3->2->1,然后将4->3->2->1看成一个整体,让这个整体的next指向null;
    (ii)假设2->3->4已经反转好,已经成为了4->3->2, 然后将4->3->2看成一个整体,让这个整体的next指向1;
    (iii)接下来问题变成了反转2->3->4
    假设3->4已经反转好,已经成为了4->3, 然后将4->3看成一个整体,让这个整体的next指向2;
    (iv)然后问题变成了反转3->4
    假设4(实际上是4->NULL)已经反转好,已经成为了4(其实是head->4), 然后将4(其实是head->4)看成一个整体,让这个整体的next指向3;
    (v)然后问题变成了反转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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容