在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
1、解决方案
- 我们重新构建一个链表来存放不重复的节点,设置一个引用,遍历原链表,遇到重复的节点往下走,一直到其后继节点与当前节点不相同,此时,我们继续向下走,判断这个后继节点本身是否是重复的,若是,继续遍历,若不是,我们将其存入我们新构建的链表。
2、方法实现
public Node deleteDuplication() {
Node newHead = new Node(-1);
Node tmpHead = newHead;
Node cur = this.head;
while (cur != null) {
if(cur.next != null && cur.data == cur.next.data) {
while (cur.next != null && cur.data == cur.next.data) {
cur = cur.next;
}
cur = cur.next;
newHead.next = cur;
}else {
newHead.next = cur;
newHead = cur;
cur = cur.next;
}
}
return tmpHead.next;
}