一、输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
// 利用栈后进先出的特性,先将元素入栈,
// 再将元素出栈,放入数组中
// 返回数组
Stack<ListNode> stack = new Stack<ListNode>();
// 定义变量,变量和head相同
ListNode tmp = head;
// 将所有的元素入栈
while(tmp != null){
stack.push(tmp);
tmp = tmp.next;
}
// 将元素出栈,并且存入到数组中
int sz = stack.size();
int[] a = new int[sz];
for(int i = 0;i < sz;i++){
a[i] = stack.pop().val;
}
return a;
}
}
二、定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
// 设置两个指针,一个表示当前指针,一个是头指针
ListNode pCur = head;
ListNode pPrev = null;
while(pCur != null){
// 定义一个指针存储当前指针的下一个指针
ListNode next = pCur.next;
pCur.next = pPrev;
pPrev = pCur;
pCur = next;
}
return pPrev;
}
}
三、
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
// 递归的方式获取每一个节点的next和random
// 使用map存储键值对
class Solution {
// 创建Map存放键值对
Map<Node,Node> cur = new HashMap<Node,Node>();
public Node copyRandomList(Node head) {
if(null == head){
return null;
}
// 若没有创建节点,则创建节点,containsKey判断对应节点有没有存在
if(!cur.containsKey(head)){
// 获取当前节点的值
Node va = new Node(head.val);
// 将其存入哈希表中
cur.put(head,va);
// head节点的下一个节点为键值对中的键
va.next = copyRandomList(head.next);
va.random = copyRandomList(head.random);
}
return cur.get(head);
}
}