leetcode: Remove Duplicates from Sorted List II

问题描述:

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

原问题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

问题分析

  这个问题有一个思路就是在链表里头从头到尾遍历的时候用count来记录当前元素出现的次数。在最开始的时候设置count = 1,然后每次判断cur和cur.next的值是否相等,如果相等,则count++,否则就要看count的值,如果count == 1,说明当前的这个值是没有出现过重复元素的,则我们需要调整指针。否则说明这个元素出现过若干次,那么只需要重置count = 1,不需要调整指针。

  最后只需要返回这个调整后的链表的头就可以了。在具体的实现里,为了找到这个调整后的链表头,我们首先定义了一个res的临时节点,它的next指向head。同时还有一个指针prev也和res相同。然后在每次调整链表的时候将prev.next = cur。这样可以在一边判断的时候一边调整链表。

  详细的代码实现如下:

/**
 * 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 null;
        ListNode res = new ListNode(0);
        res.next = head;
        ListNode prev = res, curr = head;
        int count = 1;
        while(curr.next != null) {
            if(curr.next.val == curr.val) {
                count++;
            } else {
                if(count == 1) {
                    prev.next = curr;
                    prev = curr;
                } else {
                    count = 1;
                }
            }
            curr = curr.next;
        }
        if(count == 1) prev.next = curr;
        else prev.next = null;
        return res.next;
    }
}

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2304227