学习剑指offer 第二天
06 从尾到头打印链表
- 解析
法一:建一个长度为size的数组,也就分为两步:找出数组长度+构造新数组
public int[] reversePrint(ListNode head) {
//首先建立一个长度的size的数组,第一步就要获取链表长度
int size = 0;
ListNode temp = head;
while(head != null){
size++;
head = head.next;
}
int[] result = new int[size];
while(temp != null){
result[--size] = temp.val;
temp = temp.next;
}
return result;
}
法二:使用栈的后入先出原理
public int[] reversePrint(ListNode head) {
//使用栈的后入先出原理
Deque<Integer> stack = new LinkedList<>();
while(head != null){
stack.push(head.val);
head = head.next;
}
int[] result = new int[ stack.size()];
int index = 0;
while(!stack.isEmpty()){
result[index++] = stack.pop();
}
return result;
}
24 反转链表
- 解析
只需要反转指针即可
class Solution {
public int[] reversePrint(ListNode head) {
//使用栈的后入先出原理
Deque<Integer> stack = new LinkedList<>();
while(head != null){
stack.push(head.val);
head = head.next;
}
int[] result = new int[ stack.size()];
int index = 0;
while(!stack.isEmpty()){
result[index++] = stack.pop();
}
return result;
}
}
35 复杂链表的复制
- 题目描述
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。 - 解析
使用哈希表+递归
哈希表用来存储旧节点-新节点的映射
使用递归不断创建没有遍历到的节点
class Solution {
//原节点 -> 新节点
Map<Node, Node> mymap = new HashMap<>();
public Node copyRandomList(Node head) {
if(head == null) return null;
Node new_head = new Node(head.val);
mymap.put(head, new_head);
if(head.next != null){
if(mymap.containsKey(head.next)){
new_head.next = mymap.get(head.next);
}else{
Node new_next = copyRandomList(head.next);
new_head.next = new_next;
}
}
if(head.random != null){
if(mymap.containsKey(head.random)){
new_head.random = mymap.get(head.random);
}else{
Node new_random = copyRandomList(head.random);
new_head.random = new_random;
}
}
return new_head;
}
}