题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解决思路
代码实现
public void delRepetition(){
//首先判断表头是否为空
if(this.head == null){
return ;
}
Node cur = this.head;
Node newHead = new Node(-1); //创建哑结点
Node tmp = newHead;
//遍历单链表,条件为cur指向的结点对象不为空
while(cur != null){
if(cur.next != null && cur.target == cur.next.target){
while(cur.next != null && cur.target == cur.next.target){
cur = cur.next;
}
cur = cur.next;
}else{
tmp.next = cur;
cur = cur.next;
tmp = tmp.next;
}
}
tmp.next = null; //一定要把tmp指向的结点的引用置空
this.head = newHead.next; //新的表头为哑结点的next引用所指向的结点对象
}