首页 > 代码库 > Remove Duplicates from Sorted List

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.

方法

遍历一遍Linked List,将相同的元素删除,即可。
	    public ListNode deleteDuplicates(ListNode head) {
	        ListNode first = head;
	        ListNode second;
	        while(first != null){
	            second = first.next;
	            if((second != null) && (second.val == first.val)){
	                first.next = second.next;
	            }else{
	                first = second;
	            }
	        }
	        return head;
	    }