LeetCode 分类练习(5)—— 链表相关习题(1)

206. Reverse Linked List

Reverse a singly linked list.

click to show more hints.

Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
package com.leetcode.linked_list;


public class Reverse_Linked_List {
    // 非递归写法
//  public ListNode reverseList(ListNode head) {
//      ListNode newHead = null;
//        while(head!=null){
//            ListNode next = head.next;
//            head.next = newHead;
//            newHead = head;
//            head = next;
//        }
//        return newHead;
//  }

    // 递归写法
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;

        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }


}

92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
package com.leetcode.linked_list;

import java.util.Arrays;

public class Reverse_Linked_List_II {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == n || head == null || head.next == null)
            return head;

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;

        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }
        ListNode start = pre.next;
        ListNode then = start.next;

        for (int i = 0; i < n - m; i++) {
            start.next = then.next;
            then.next = pre.next;
            pre.next = then;
            then = start.next;
        }
        return dummy.next;
    }

//        public ListNode reverseBetween(ListNode head, int m, int n) {
//        if (head.next == null || head == null || m == n)
//            return head;
//
//        ListNode pos_n = head;
//        int pos = 1;
//        ListNode pre_m;
//        ListNode pos_m;
//        if (m != 1) {
//            pre_m = head;
//            while (pos < m - 1) {
//                pre_m = pre_m.next;
//                pos++;
//            }
//            pos_m = pre_m.next;
//        } else {
//            pre_m = null;
//            pos_m = head;
//        }
//
//
//        while (pos < n) {
//            pos_n = pos_n.next;
//            pos++;
//        }
//        ListNode after_n = pos_n.next;
//
//        if (after_n != null){
//            pos_n = pos_n.next;
//            after_n = pos_n.next;
//        }
//
//
//        ListNode newHead = after_n;
//        while (m <= n) {
//            ListNode nextNode = pos_m.next;
//            pos_m.next = newHead;
//            newHead = pos_m;
//            pos_m = nextNode;
//            m++;
//        }
//        if (pre_m != null)
//            pre_m.next = newHead;
//
//        if (pre_m == head)  // m == 2 的情况
//            return pre_m;
//
//        if (after_n == null || pre_m == null)   // 对于 m == 1 或是 n == list.length 的情况
//            return newHead;
//
//        return head;
//    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Reverse_Linked_List_II reverse = new Reverse_Linked_List_II();

        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 7, 5, 4, 3));
        ListNode.printLinkedList(head);
        ListNode.printLinkedList(reverse.reverseBetween(head, 3, 7));

        ListNode head_1 = creator.createLinkedList(Arrays.asList(5));
        ListNode.printLinkedList(head_1);
        ListNode.printLinkedList(reverse.reverseBetween(head_1, 1, 1));

        ListNode head_2 = creator.createLinkedList(Arrays.asList(3, 5));
        ListNode.printLinkedList(head_2);
        ListNode.printLinkedList(reverse.reverseBetween(head_2, 2, 2));

//        ListNode head_3 = creator.createLinkedList(Arrays.asList(3, 5, 6, 7, 8));
//        ListNode.printLinkedList(head_3);
//        ListNode.printLinkedList(reverse.reverseBetween(head_3, 1, 5));
//        ListNode.printLinkedList(reverse.reverseBetween(head_3, 2, 5));
//        ListNode.printLinkedList(reverse.reverseBetween(head_3, 1, 4));

        ListNode head_4 = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5));
        ListNode.printLinkedList(head_4);
        ListNode.printLinkedList(reverse.reverseBetween(head_4, 1, 4));


    }
}

83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
package com.leetcode.linked_list;

import java.util.Arrays;

public class Remove_Duplicates_from_Sorted_List_II {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = head;

        while (cur != null) {
            while (cur.next != null && cur.val == cur.next.val) {
                cur = cur.next;
            }
            if (pre.next == cur) {
                pre = pre.next;
            } else {
                pre.next = cur.next;
            }
            cur = cur.next;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Remove_Duplicates_from_Sorted_List_II remove = new Remove_Duplicates_from_Sorted_List_II();

//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 7, 5, 4, 3));
        ListNode head = creator.createLinkedList(Arrays.asList(1, 1));
        ListNode.printLinkedList(remove.deleteDuplicates(head));

    }
}

86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
package com.leetcode.linked_list;

import java.util.Arrays;

public class Partition_List {
    public ListNode partition(ListNode head, int x) {
        ListNode dummy1 = new ListNode(0), dummy2 = new ListNode(0);  //dummy heads of the 1st and 2nd queues
        ListNode curr1 = dummy1, curr2 = dummy2;      //current tails of the two queues;
        while (head != null) {
            if (head.val < x) {
                curr1.next = head;
                curr1 = head;
            } else {
                curr2.next = head;
                curr2 = head;
            }
            head = head.next;
        }
        curr2.next = null;          //important! avoid cycle in linked list. otherwise u will get TLE.
        curr1.next = dummy2.next;
        return dummy1.next;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Partition_List partition_list = new Partition_List();

//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 2, 1, 2));
//        ListNode.printLinkedList(head);
//        ListNode.printLinkedList(partition_list.partition(head, 3));

        ListNode head = creator.createLinkedList(Arrays.asList(1, 4, 3, 2, 5, 2));
        ListNode.printLinkedList(head);
        ListNode.printLinkedList(partition_list.partition(head, 3));
    }
}

328. Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input. 
The first node is considered odd, the second node even and so on ...
package com.leetcode.linked_list;

import java.util.ArrayList;
import java.util.Arrays;

public class Odd_Even_Linked_List {
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null || head.next.next == null)
            return head;
        ListNode dummy1 = new ListNode(0);
        ListNode dummy2 = new ListNode(0);
        ListNode curr1 = dummy1, curr2 = dummy2;
        int pos = 1;
        while (head != null){
            if (pos % 2 == 1){
                curr1.next = head;
                curr1 = head;
            }else {
                curr2.next = head;
                curr2 = head;
            }
            head = head.next;
            pos++;
        }
        curr1.next = dummy2.next;
        curr2.next = null;
        return dummy1.next;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Odd_Even_Linked_List odd_even_linked_list = new Odd_Even_Linked_List();

//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
//        ListNode head = creator.createLinkedList(Arrays.asList(1));
//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2));
        ListNode head = creator.createLinkedList(new ArrayList<>());

        ListNode.printLinkedList(head);
        ListNode.printLinkedList(odd_even_linked_list.oddEvenList(head));
    }

}

2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
package com.leetcode.linked_list;

import java.util.Arrays;

public class Add_Two_Numbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + carry;
            ListNode node = new ListNode(sum % 10);
            carry = sum / 10;
            cur.next = node;
            cur = node;

            l1 = (l1 == null) ? l1 : l1.next;
            l2 = (l2 == null) ? l2 : l2.next;
        }
        return dummy.next;
    }

    /*
    * 1560 / 1562 test cases passed.
    * Input:
    * [2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9]
    * [5,6,4,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,2,4,3,9,9,9,9]
    * 溢出
    * */
//    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//        long num1 = 0;
//        int pos = 0;
//        while (l1 != null) {
//            num1 += (long) (l1.val * Math.pow(10, pos++));
//            l1 = l1.next;
//        }
//
//        long num2 = 0;
//        pos = 0;
//        while (l2 != null) {
//            num2 += (long) (l2.val * Math.pow(10, pos++));
//            l2 = l2.next;
//        }
//
//        long sum = num1 + num2;
//        ListNode dummy = new ListNode(0);
//        if (sum == 0) {
//            return dummy;
//        }
//
//        ListNode cur = dummy;
//        while (sum != 0) {
//            ListNode node = new ListNode((int) (sum % 10));
//            cur.next = node;
//            cur = node;
//            sum /= 10;
//        }
//        cur.next = null;
//        return dummy.next;
//    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Add_Two_Numbers add_two_numbers = new Add_Two_Numbers();

//        ListNode l1 = creator.createLinkedList(Arrays.asList(1, 2, 3));
//        ListNode l2 = creator.createLinkedList(Arrays.asList(1));

        // 溢出的情况,将 int 换为 long
//        ListNode l1 = creator.createLinkedList(Arrays.asList(9));
//        ListNode l2 = creator.createLinkedList(Arrays.asList(1, 9, 9, 9, 9, 9, 9, 9, 9, 9));

        ListNode l1 = creator.createLinkedList(Arrays.asList(3, 9, 9, 9, 9, 9, 9, 9, 9, 9));
        ListNode l2 = creator.createLinkedList(Arrays.asList(7));

        ListNode.printLinkedList(add_two_numbers.addTwoNumbers(l1, l2));
    }

}

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
package com.leetcode.linked_list;

import java.util.Arrays;
import java.util.Stack;

public class Add_Two_Numbers_II {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> stack_1 = new Stack<>();
        Stack<Integer> stack_2 = new Stack<>();
        while (l1 != null) {
            stack_1.push(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            stack_2.push(l2.val);
            l2 = l2.next;
        }
        ListNode cur = null;
        int carry = 0;
        while (!stack_1.isEmpty() || !stack_2.isEmpty() || carry != 0) {
            int sum = (stack_1.isEmpty() ? 0 : stack_1.pop()) + (stack_2.isEmpty() ? 0 : stack_2.pop()) + carry;
            ListNode node = new ListNode(sum % 10);
            carry = sum / 10;
            node.next = cur;
            cur = node;
        }
        return cur;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Add_Two_Numbers_II add_two_numbers = new Add_Two_Numbers_II();

//        ListNode l1 = creator.createLinkedList(Arrays.asList(1, 2, 3));
//        ListNode l2 = creator.createLinkedList(Arrays.asList(1));

//        ListNode l1 = creator.createLinkedList(Arrays.asList(1, 2, 3));
//        ListNode l2 = creator.createLinkedList(Arrays.asList(1, 2, 3, 2, 1, 3, 1, 1));

        ListNode l1 = creator.createLinkedList(Arrays.asList(5));
        ListNode l2 = creator.createLinkedList(Arrays.asList(5));

        ListNode.printLinkedList(add_two_numbers.addTwoNumbers(l1, l2));

    }
}

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
package com.leetcode.linked_list;

// 203. Remove Linked List Elements

import java.util.Arrays;

public class Remove_Linked_List_Elements {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == val) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Remove_Linked_List_Elements remove = new Remove_Linked_List_Elements();

//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 7, 5, 4, 3));
        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 1));

        ListNode.printLinkedList(head);
        ListNode.printLinkedList(remove.removeElements(head, 1));
    }
}

82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

package com.leetcode.linked_list;

import java.util.Arrays;

public class Remove_Duplicates_from_Sorted_List_II {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = head;

        while (cur != null) {
            while (cur.next != null && cur.val == cur.next.val) {
                cur = cur.next;
            }
            if (pre.next == cur) {
                pre = pre.next;
            } else {
                pre.next = cur.next;
            }
            cur = cur.next;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        LinkedListCreator creator = new LinkedListCreator();
        Remove_Duplicates_from_Sorted_List_II remove = new Remove_Duplicates_from_Sorted_List_II();

//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 7, 5, 4, 3));
        ListNode head = creator.createLinkedList(Arrays.asList(1, 1));
        ListNode.printLinkedList(remove.deleteDuplicates(head));

    }
}

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.

package com.leetcode.linked_list;

public class Merge_Two_Sorted_Lists {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                cur.next = l2;
                l2 = l2.next;
            } else {
                cur.next = l1;
                l1 = l1.next;
            }
            cur = cur.next;
        }
        cur.next = (l2 == null) ? l1 : l2;

        return dummy.next;
    }
}

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.
package com.leetcode.linked_list;

import java.util.Arrays;

public class Swap_Nodes_in_Pairs {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = head;
        ListNode beh = head.next;
        while (beh != null) {
            cur.next = beh.next;
            beh.next = pre.next;
            pre.next = beh;

            pre = cur;
            cur = cur.next;
            if (cur == null)
                break;

            beh = cur.next;
        }
        return dummy.next;
    }

    public static void main(String[] args){
        LinkedListCreator creator = new LinkedListCreator();
        Swap_Nodes_in_Pairs swap = new Swap_Nodes_in_Pairs();

//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 7, 5, 4, 3));
        ListNode head = creator.createLinkedList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 7, 5, 4));

        ListNode.printLinkedList(head);
//        ListNode head = creator.createLinkedList(Arrays.asList(1, 2));
        ListNode.printLinkedList(swap.swapPairs(head));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值