3.从尾到头打印链表
题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
题解:
- 遍历节点,将数据压栈
- 弹栈,数据存储在数组中
public int[] reversePrint(ListNode head) {
int index = 0;
if (head == null){
return new int[0];
}
Stack stack = new Stack<Integer>();
while (head != null){
stack.push(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
while (!stack.empty()){
res[index] = (int)stack.pop();
index++;
}
return res;
}
4.反转链表
题目:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
题解:
使用栈结构进行反转
注意:
在对栈内弹出的节点ListNode进行重新装配形成list的过程中,注意将ListNode.next置为null,否则会出现环
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack = new Stack<>();
while (head != null){
stack.push(head);
head = head.next;
}
ListNode temp = new ListNode(0);
ListNode res = temp;
while (!stack.empty()){
ListNode ln = stack.pop();
//注意:将弹出的ListNode的next置为空,否则会形成闭环
ln.next = null;
temp.next = ln;
temp = temp.next;
}
return res.next;
}
5.复杂链表的复制
题目:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
题解:
考察深拷贝,难点在于比如创建新节点1,而旧节点的random节点为5,此时新的链表中并不存在节点5,就会造成指针指向原节点的错误。
-
使用map将原node与新node进行一一对应
-
第一次遍历得到新旧节点的对应关系
-
旧节点的next节点对应的新节点赋值给新节点的next
-
newNode.next = map(OldNode.next)
-
map.get(cur).next = map.get(cur.next);
-
-
random节点以此类推
public Node copyRandomList(Node head) {
HashMap<Node, Node> map = new HashMap<>();
Node cur = head;
while (cur != null){
map.put(cur,new Node(cur.val));
cur = cur.next;
}
cur = head;
while (cur != null){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
哪怕他今生一世暗淡无光,可他在自己生命的历程中,仍然还有值得骄傲和怀恋的东西啊!