83. Remove Duplicates from Sorted List

/**
 * 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 null;
      }
      ListNode tail = head;
      while(tail.next != null){
        if( tail.next.val != tail.val){
          tail = tail.next;
        }else{
          tail.next = tail.next.next;
        }
      }
      return head;
    }
}

 

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

posted on 2018-07-18 09:16  猪猪🐷  阅读(53)  评论(0)    收藏  举报

导航