LeetCode----- 83.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.

給定已排序好的鏈表,刪除鏈表中所有的重複項,使得每個元素只顯示一次。

解題思路:用兩個指針pre,point分別指向鏈表的前一個結點和下一個結點,當這2個結點中的數據不相等時,兩個指針後移;當2個結點的數據相等時,前一個結點的next指向後一個結點的next,從而刪除了相等的結點。

public class RemoveDuplicatesfromSortedList {
    public static ListNode deleteDuplicates(ListNode head) {
    	if(head == null || head.next == null) {
    		return head;
    	}
    	ListNode pre = head;
    	ListNode point = head.next;
    	while(point != null) {
    		if(pre.val == point.val) {
    			pre.next = point.next;
    		}else {
    			pre = pre.next;
    		}
    		point = point.next;
    	}
        return head;
    }
	
	public static void main(String[] args) {
		ListNode l10 = new ListNode(1);
		ListNode l11 = new ListNode(1);
		ListNode l12 = new ListNode(2);		
		ListNode l13 = new ListNode(3);
		ListNode l14 = new ListNode(3);
		l10.next = l11;
		l11.next = l12;
		l12.next = l13;
		l13.next = l14;
		l14.next = null;
		
		ListNode node = deleteDuplicates(l10);
		while(node != null) {
			if(node.next == null) {
				System.out.println(node.val);
			}else{
				System.out.print(node.val +"->");
			}
			node = node.next;
		}

	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章