java 删除链表中所有的重复元素
作者:互联网
1. 题目考点
- 使用哑结点
- 链表节点删除
2. 考点解析
public ListNode deleteDuplicates (ListNode head) {
// write code here
if (head == null) return null;
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode p = head, pre = newHead;
while (p != null && p.next != null) {
// 关键:找到重复元素的起点
if (p.val == p.next.val) {
ListNode temp = p.next;
while (temp != null && temp.val == p.val) {
temp = temp.next;
}
pre.next = temp;
p = temp;
} else {
pre = p;
p = p.next;
}
}
return newHead.next;
}
标签:ListNode,删除,temp,next,链表,val,java,null,newHead 来源: https://blog.csdn.net/qq_37417648/article/details/113623845