82. Remove Duplicates from Sorted List II

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


82. Remove Duplicates from Sorted List II

这个特别生疏, 感觉第一遍不是自己做的, 要自己把这道题想出来
这个是闫老师的代码


class Solution {
    public ListNode deleteDuplicates(ListNode head) {
      ListNode dummy = new ListNode(-1);
      dummy.next = head;
      
      ListNode tail = dummy;
      while( tail.next != null){
        ListNode fast = tail.next;
        while(fast.next != null && fast.next.val == tail.next.val){
          fast = fast.next;
        }
        if(fast != tail.next){  ////////
          tail.next = fast.next;
        }else{
          tail = tail.next;
        }
      }
      return dummy.next;
    }
}

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

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

 

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

导航