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.

在一个有序的链表中删除重复的元素,使每个元素只能出现一次。做链表删除节点的问题,我们一般采用一个辅助节点helper来记录头结点,用于返回。对于这道题目,头结点肯定不会删除,因此我们直接将helper节点指向头结点即可。如果head.val = head.next.val 就让head.next = head.next.next,这样就跳过了值相同的节点;否则head往前移动,head = head.next,知道遍历完所有的元素。代码如下:
/**
 * 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 helper = head;
        while(helper.next != null) {
            if(helper.next.val == helper.val) 
                helper.next = helper.next.next;
            else
                helper = helper.next;
        }
        return head;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2275761