题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
这道题需要注意的是,把重复元素全部删除而不是保留一个。指针需要推演推演。
运行时间:23ms
占用内存:9352k
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead == null)
return null;
ListNode Head = new ListNode(-1);
Head.next = pHead;
ListNode cur = Head; //指向确定的一定不会重复的元素
ListNode p = cur.next; //作为遍历整个链表的指针
while(cur != null && cur.next != null){
boolean isSame = false;
while(p.next != null && p.val == p.next.val){
p = p.next;
isSame = true;
}
if(isSame)
cur.next = p.next;
else
cur = cur.next;
p = p.next;
}
return Head.next;
}
}