Java for LeetCode 083 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.

解题思路:

修改上题代码即可,JAVA实现如下:

public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
			return head;
		ListNode temp = head.next;
		if (temp.val == head.val) {
			while (temp.val == head.val) {
				temp = temp.next;
				if (temp == null) {
					head.next = null;
					return head;
				}
			}
			head.next = temp;
		}
		temp = head.next;
		ListNode last = head;
		while (temp != null && temp.next != null) {
			if (temp.val != temp.next.val) {
				last.next = temp;
				temp = temp.next;
				last = last.next;
				continue;
			}
			last.next = temp;
			last=last.next;
			while (temp.val == last.val) {
				temp = temp.next;
				if (temp == null) {
					last.next = null;
					return head;
				}
			}
		}
		last.next = temp;
		return head;
	}

 

posted @ 2015-05-19 12:44  TonyLuis  阅读(135)  评论(0编辑  收藏  举报