题目:在一个排序的链表中,如何删除重复的节点?
思路:删除重复节点同样要考虑边界值的问题,头节点为重复,尾节点为重复,整个链表都为重复。删除重复节点时。
自己写的错误代码,注意该代码无法运行。运行错误
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null) return null;
ListNode pNode = pHead;
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
dummy.next = pHead;
while(pNode!=null){
if(pNode.next!=null&&pNode.val==pNode.next.val){
while(pNode.next!=null&&pNode.val==pNode.next.val) {
pNode = pNode.next;
}
pNode = pNode.next;
pre.next = pNode;
pre = pNode;
}
pNode = pNode.next;
pre = pNode;
}
return dummy.next;
}
}
参考剑指offer。设置一个bool值判断当前节点是不是需要删除。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode head)
{
if(head==null) return null;
ListNode pNode = head;
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
dummy.next = head;
while(pNode!=null){
ListNode pNext = pNode.next;
boolean needDel = false;
if(pNext!=null&&pNode.val==pNext.val)
needDel = true;
if(!needDel){
pre = pNode;
pNode = pNext;
}
else{
int value = pNode.val;
ListNode ptoBeDel = pNode;
while(ptoBeDel!=null&&ptoBeDel.val==value){
ptoBeDel = ptoBeDel.next;
}
pNode = ptoBeDel;
pre.next = ptoBeDel;
}
}
return dummy.next;
}
}