题解全部迁移到 Github ,现已经完成53题

leetcode 83: Remove Duplicates from Sorted List

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3
Java:
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode p = head;
        ListNode q = head.next;
        while(q != null){
            if(p.val == q.val){
                p.next = q.next;
            }
            else{
                p = p.next;
            }
            q = q.next;
        }
        return head;
        
    }
}

leetcode 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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
Java:
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode smaller = new ListNode(0);
        ListNode greater = new ListNode(0);
        ListNode ps = smaller;
        ListNode pr = greater;
        for(ListNode p = head; p != null; p=p.next){
            if(p.val < x){
                ps.next = p;
                ps = ps.next;
            }
            else{
                pr.next = p;
                pr = pr.next;
            }
        }
        ps.next = greater.next;
        pr.next = null;
        return smaller.next;        
    }
}

leetcode 160: Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

Java:
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }
        ListNode p = headA;
        ListNode q = headB;
        while(p != q){
            p = p == null ? headB : p.next;
            q = q == null ? headA : q.next;
        }
        return p; 
    }
}

LeetCode 203: Remove Linked List Elements

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

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
Java:
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null){
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p = dummy;
        while(p.next != null){
            if(p.next.val == val){
                p.next = p.next.next;
            }
            else{
                p = p.next;
            }
            
        }
        return dummy.next;    
    }
}