JZ35 复杂链表的复制 ⭐⭐⭐
最开始连题目都没看懂。思路:哈希法:将旧结点和新结点的映射关系存储到hash表中,方便后续查找。这样新链表和旧链表每个结点的指向就有了关联。两次循环链表,先创建结点复制label,再修改 random 和 next 指针的指向。最后返回头结点的映射。
时间和空间复杂度:O(n) 遍历和创建哈希表,哈希表存储结点地址映射
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
Map<RandomListNode, RandomListNode> map = new HashMap<>();
for (RandomListNode cur = pHead; cur != null; cur = cur.next) {
map.put(cur, new RandomListNode(cur.label));
}
for (RandomListNode cur = pHead; cur != null; cur = cur.next) {
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
}
return map.get(pHead);
}
}
JZ76 删除链表中重复的结点 ⭐⭐
方法一:遍历链表,每次比较相邻两个节点,如果遇到了两个相邻节点相同,则新开内循环将这一段所有的相同都遍历过去。
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;
}
}
方法二:哈希。这个我没想到。这里给出一种通用的解法,有序无序都可以使用,即利用哈希表来统计是否重复。
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;
}
}
JZ18 删除链表的节点 ⭐
基础题直接给代码吧
public class Solution {
public ListNode deleteNode (ListNode head, int val) {
if (head.val == val) return head.next;
ListNode pre = head;
while (pre.next != null) {
if (pre.next.val == val) pre.next = pre.next.next;
pre = pre.next;
}
return head;
}
}