leetcode: 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.

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

问题分析

  这个问题和之前讨论过的移除重复元素的问题很接近。它们有一个细微的差别就是在前一个问题中,对于有任何重复的元素,它们将不能包含在结果链表中,而这个是要求重复的元素有一个要包含在结果连表中。虽然有这么一个细微的差别,但是它们的基本解决思路还是很近似的。

  我们通过一个临时的ListNode来保存指向head前一个元素,并将它设置为pre。然后将cur = head。这样每次根据cur.next != null的循环去判断cur.val == cur.next.val。如果不相等说明cur的下一个元素就要和当前元素不同了,那么需要将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 || head.next == null) return head;
        ListNode res = new ListNode(0);
        res.next = head;
        ListNode pre = res, cur = head;
        while(cur.next != null) {
            if(cur.val != cur.next.val) {
                pre.next = cur;
                pre = cur;
            }
            cur = cur.next;
        }
        pre.next = cur;
        return res.next;
    }
}

  

猜你喜欢

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