Remove Duplicates from Unsorted List
Question:
Write code to remove duplicates from an unsorted linked list.
Example
Given 1->3->2->1->4.
Return 1->3->2->4
Lesson Learned:
- 删除Node时,因为可能去掉的是最后一个element,loop会指向null,所以不能,仅仅判断loop.next,要将loop!=null也作为一个跳出循环的条件
- 每当出现cur = cur.next的时候都要想想,会不会出现cur是null,或cur.next==null会影响下一轮的循环条件
if (cur.next != null) { cur = cur.next; }
Code:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: head node
*/
public ListNode removeDuplicates(ListNode head) {
// Write your code here
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
while (cur.next != null) {
ListNode loop = cur;
int val = cur.val;
// 因为可能去掉的是最后一个element,loop会指向null,所以不能
// 仅仅判断loop.next,要将loop!=null也作为一个跳出循环的条件
// 可能出现
while (loop.next != null && loop != null) {
if (loop.next.val == cur.val) {
loop.next = loop.next.next;
continue;
}
loop = loop.next;
}
// 每当出现cur = cur.next的时候都要想想,会不会出现cur是null
// 或cur.next==null会影响下一轮的循环条件
if (cur.next != null) {
cur = cur.next;
}
}
return head;
}
}