AcWing 29. 删除链表中重复的节点(java)
原题链接
中等
作者:
YOLO6
,
2024-01-09 10:57:24
,
所有人可见
,
阅读 37
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplication(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode p = dummy, q = p.next;
// emphsize the p and q
while(p.next != null) {
// p no need to enter repeated parts, if q repeated , then move behind
while(q != null && p.next.val == q.val) {
q = q.next;
}
// after moved, start to judge the p
if(p.next.next == q) p = p.next;
else p.next = q;
}
return dummy.next;
}
}