题解 | #删除链表中重复的结点#
删除链表中重复的结点
http://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
/*class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pHead ListNode类
* @return ListNode类
*/
export function deleteDuplication(pHead: ListNode): ListNode {
// write code here
if(!pHead || !pHead.next) {
return pHead;
}
// const nodeSet = new Set();
// let p1 = pHead;
// while(p1.next) {
// if(p1.val === p1.next.val) {
// nodeSet.add(p1.val);
// }
// p1 = p1.next;
// }
// const dummy = new ListNode(0);
// dummy.next = pHead;
// let prev = dummy, cur = pHead;
// while(cur) {
// if(nodeSet.has(cur.val)) {
// cur = cur.next;
// prev.next = cur;
// } else {
// prev = prev.next;
// cur = cur.next;
// }
// }
// return dummy.next;
// ===============================
const dummy = new ListNode(0);
dummy.next = pHead;
let cur = dummy;
let flag = false;
while(cur.next) {
while(cur.next.next?.val === cur.next?.val) {
cur.next = cur.next.next;
flag = true;
}
if(flag === true) {
cur.next = cur.next.next;
flag = false;
} else {
cur = cur.next;
}
}
return dummy.next;
}