题目:
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
代码:
public class Test28 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode deleteDuplicates(ListNode head) {
if (head!=null && head.next!=null && head.next.val == head.val) {
while (head != null && head.next != null && head.next.val == head.val){
while (head != null && head.next != null && head.next.val == head.val) {
head = head.next;
}
head=head.next;
}
}
if (head==null || head.next==null) {
return head;
}
ListNode result=head;
ListNode lastNode=head;
ListNode node=head.next;
while (node.next != null) {
if (node.val==node.next.val) {
while (node!=null && node.next!=null && node.val == node.next.val) {
node = node.next;
}
if (node==null || node.next==null) {
lastNode.next=null;
break;
}else{
node=node.next;
lastNode.next=node;
}
}else{
lastNode.next=node;
lastNode=node;
node=node.next;
}
}
return result;
}
}