[链表]83. Remove Duplicates from Sorted List

83. Remove Duplicates from Sorted List

链表很简单的题,但是对链表基本结构都理解的很透彻才行!!

牢记!

JAVA 1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return head;
        
        for(ListNode pre = head, cur = head.next; cur != null; cur = pre.next){
            if(pre.val == cur.val){
                pre.next = cur.next;//Important step!
            }else{
                pre = cur;
            }
        }
        return head;
        
    }
}

JAVA 2 Solution's answer

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode cur = head;
        while(cur!=null){
            ListNode nex = cur;
            while(nex.next != null && nex.val == nex.next.val){
                nex = nex.next;
            }
            cur.next = nex.next;//Must have!
            cur = nex.next;
            
            
        }
        return head;
        
    }
}

你可能感兴趣的:([链表]83. Remove Duplicates from Sorted List)