您的位置:首页 > 其它

Remove Duplicates from Sorted List II

2014-11-23 04:53 429 查看


Fair Remove
Duplicates from Sorted List II
Show Result My Submissions

28%

Accepted

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct numbers from the original list.
Example

Given 
1->2->3->3->4->4->5
,
return 
1->2->5
.

Given 
1->1->1->2->3
, return 
2->3
.

KEY: 

1. use dummy node. Because the head of the original node might be changed.

2. every iteration we compare head.next.val with head.next.next.val. Save head.next.val if the the two adjacent nodes are equal. And use a while loop to delete all the nodes with the same value. The deletion starts from
head.next.

</pre><pre name="code" class="java">
</pre><p></p><p><pre name="code" class="java">/**
* Definition for ListNode
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of the linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;

while (head.next != null && head.next.next != null) {
if (head.next.val == head.next.next.val) {
int val = head.next.val;
while (head.next != null && head.next.val == val) {
head.next = head.next.next;
}
} else {
head = head.next;
}
}
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode LinkedList