LinkedList基础


  • 翻转链表

  • 链表求中点

  • 合并两个排序链表

翻转链表

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode prev = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = prev;
            prev = head;
            head = tmp;
        }
        return prev;
    }
}

有可能会问递归的做法。

public class Solution {
    public ListNode reverseList(ListNode head) {
        return reverse(head, null);
    }
    private ListNode reverse(ListNode head, ListNode prev) {
        if (head == null) return prev;

        ListNode next = head.next;
        head.next = prev;
        return reverse(next, head);
    }
}

链表的中点

两点注意:

  • 快指针在慢指针的下一个节点
  • while循环的判断条件是快指针不为null,快指针的下一个也不为null
public class Solution {
    /**
     * @param head: the head of linked list.
     * @return: a middle node of the linked list
     */
    public ListNode middleNode(ListNode head) { 
        // Write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}

合并两个排序链表

public class Solution {
    /**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // write your code here
        if(l1 == null && l2 == null){
            return null;
        }
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                head.next = l1;
                head = l1;
                l1 = l1.next;
            } else {
                head.next = l2;
                head = l2;
                l2 = l2.next;
            }
        }
        while(l1 != null){
            head.next = l1;
            head = l1;
            l1 = l1.next;
        }
        while(l2 != null){
            head.next = l2;
            head = l2;
            l2 = l2.next;
        }
        return dummy.next;
    }
}

results matching ""

    No results matching ""