2021-12-07 13:34:11
浏览数 (1)
题目描述
解题描述
代码语言:javascript
复制public class DeleteDuplicationInList {
static class ListNode {
public ListNode next;
public Integer val;
}
/**
* 只能删除连续的的重复数字
* @param pHead
* @return
*/
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null) { // 只有0个或1个结点,则返回
return pHead;
}
if (pHead.val.equals(pHead.next.val)) { // 当前结点是重复结点
ListNode pNode = pHead.next;
while (pNode != null && pNode.val.equals(pHead.val)) {
// 跳过值与当前结点相同的全部结点,找到第一个与当前结点不同的结点
pNode = pNode.next;
}
return deleteDuplication(pNode); // 从第一个与当前结点不同的结点开始递归
} else { // 当前结点不是重复结点
pHead.next = deleteDuplication(pHead.next); // 保留当前结点,从下一个结点开始递归
return pHead;
}
}
/**
* 删除所有重复的节点
* @param pHead
* @return
*/
public ListNode deleteDuplication2(ListNode pHead) {
if (pHead == null) {
return null;
}
// 先找出相同结点,存入 set
HashSet<Integer> set = new HashSet<>();
ListNode pre = pHead;
ListNode cur = pHead.next;
while (cur != null) {
if (cur.val.equals(pre.val)) {
set.add(cur.val);
}
pre = cur;
cur = cur.next;
}
// 再根据相同节点删除
// 先删头部
while (pHead != null && set.contains(pHead.val)) {
pHead = pHead.next;
}
if (pHead == null) {
return null;
}
// 再删中间结点
pre = pHead;
cur = pHead.next;
while (cur != null) {
if (set.contains(cur.val)) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return pHead;
}
public static void main(String[] args) {
ListNode first = new ListNode();
first.val = 1;
ListNode second = new ListNode();
second.val = 2;
ListNode third = new ListNode();
third.val = 2;
ListNode four = new ListNode();
four.val = 3;
ListNode five = new ListNode();
five.val = 2;
ListNode six = new ListNode();
six.val = 5;
first.next = second;
second.next = third;
third.next = four;
four.next = five;
five.next = six;
ListNode listNode = new DeleteDuplicationInList().deleteDuplication2(first);
System.out.println(listNode.val);
ListNode next = listNode.next;
while (null != next) {
System.out.println(next.val);
next = next.next;
}
}
}