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.

一刷
题解:
用append的思路解决linkedlist的问题会更容易一些。注意处理循环结束时的边界状态。

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

二刷:
基于82题思路修改

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null) return head;
        ListNode dummy = new ListNode(-1);
        ListNode prev = dummy;
        ListNode cur = head;
        prev.next = cur;
        while(cur!=null){
            while(cur.next!=null && cur.val == cur.next.val){
                cur = cur.next;
            }
            
            if(prev.next == cur){
                prev = prev.next;
            }
            else{
                prev.next = cur;
                prev = prev.next;
            }
            cur = cur.next;
        }
        return dummy.next;
    }
}

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