Problem:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
Analysis:
本题的是保留每一个不同的节点元素,在遍历链表的时候每次保留上一个节点的值,并进行比较。代码如下:
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode res = new ListNode(-1);
ListNode p = head;
int value = p.val;
ListNode pre = res;
pre.next = new ListNode(p.val);
pre = pre.next;
p = p.next;
while(p != null) {
if(value != p.val) {
//System.out.println("[msg1]: " + value);
ListNode temp = new ListNode(p.val);
pre.next = temp;
pre = pre.next;
value = p.val;
p = p.next;
} else {
//System.out.println("[msg2]: " + value);
while(p != null && value == p.val) {
p = p.next;
}
if(p != null) {
//System.out.println("[msg3]: " + value);
value = p.val;
ListNode temp = new ListNode(value);
pre.next = temp;
pre = pre.next;
p = p.next;
} else {
//System.out.println("[msg4]: " + value);
if(value != pre.val) {
ListNode temp = new ListNode(value);
pre.next = temp;
pre = pre.next;
}
}
}
}
return res.next;
}
}