题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
分析
注意 : 重复的节点不保留
代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
/**
* @param head
* @return
*/
public ListNode deleteDuplication(ListNode head) {
if (head == null) {
return head;
}
ListNode toolNode = new ListNode(-1);
toolNode.next = head;
ListNode pre = toolNode;
ListNode last = toolNode.next;
while (last != null) {
if (last.next != null && last.val == last.next.val) {
while (last.next != null && last.val == last.next.val) {
last = last.next;
}
pre.next = last.next;
last = last.next;
} else {
pre=pre.next;
last=last.next;
}
}
// 1 1 1
// 1 2 3 4
// x 1 1 1 1 2 2 3 4 4 5
// pre last
return toolNode.next;
}
}
相关例题