删除链表中重复的结点

删除链表中重复的结点

1、题目

图1

2、解题

1:直接删除

思路:

  1. 给链表添加一个表头。
  2. 遍历链表,每次比较相邻两个节点,如果遇到了两个相邻节点相同,则新开内循环将这一段所有的相同都遍历过去。
  3. 在第二步中这一连串相同的节点前的节点直接连上后续第一个不相同值的节点。
  4. 返回时去掉添加的表头。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
//空链表
if(pHead == null)
return null;
ListNode res = new ListNode(0);
//在链表前加一个表头
res.next = pHead;
ListNode cur = res;
while(cur.next != null && cur.next.next != null){
//遇到相邻两个节点值相同
if(cur.next.val == cur.next.next.val){
int temp = cur.next.val;
//将所有相同的都跳过
while (cur.next != null && cur.next.val == temp)
cur.next = cur.next.next;
}
else
cur = cur.next;
}
//返回时去掉表头
return res.next;
}
}

2:哈希表

思路:该题是有序链表,可以直接与旁边的元素比较,删除重复的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.*;
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
//空链表
if(pHead == null)
return null;
Map<Integer,Integer> mp = new HashMap<>();
ListNode cur = pHead;
//遍历链表统计每个节点值出现的次数
while(cur != null){
if(mp.containsKey(cur.val))
mp.put(cur.val, (int)mp.get(cur.val) + 1);
else
mp.put(cur.val,1);
cur = cur.next;
}
ListNode res = new ListNode(0);
//在链表前加一个表头
res.next = pHead;
cur = res;
//再次遍历链表
while(cur.next != null){
//如果节点值计数不为1
if(mp.get(cur.next.val) != 1)
//删去该节点
cur.next = cur.next.next;
else
cur = cur.next;
}
//去掉表头
return res.next;
}
}


删除链表中重复的结点
http://example.com/2023/10/11/del-repeated-node/
作者
Z Z
发布于
2023年10月11日
许可协议