问题1

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
做法:利用栈的特性 实现首尾反转
要点: Stack s1 =new Stack()
head.next head.val
Stack.size()获取栈大小
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public int[] reversePrint(ListNode head) {
  11. Stack<Integer> stack1 = new Stack<Integer>();
  12. while(head!=null){
  13. stack1.push(head.val);
  14. head=head.next;
  15. }
  16. int size =stack1.size();
  17. int[] a = new int[size];
  18. for(int i =0 ;i <size;i++){
  19. a[i]=stack1.pop();
  20. }
  21. return a;
  22. }
  23. }
  24. /**
  25. * Definition for singly-linked list.
  26. * public class ListNode {
  27. * int val;
  28. * ListNode next;
  29. * ListNode(int x) { val = x; }
  30. * }
  31. */

问题2:

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
这是一个改变指向问题 不等同于反转 没必要用栈来搞的复杂
用迭代做
原理
1->2->3->4->5->null
想要改变指向
利用一个中间结点 pre
一开始令pre为null next =head.next 是2
curr=head 是 1 令 curr.next=pre 完成1->null
pre =curr 变成 1
curr =next 完成当前 从1 变成2
curr.next=pre 完成 2->1 进行循环 终止条件是当curr =null时

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. ListNode prev = null;
  12. ListNode curr = head;
  13. while (curr != null) {
  14. ListNode next = curr.next;
  15. curr.next = prev;
  16. prev = curr;
  17. curr = next;
  18. }
  19. return prev;
  20. }
  21. }

问题3:

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

image.png

  1. /*
  2. // Definition for a Node.
  3. class Node {
  4. int val;
  5. Node next;
  6. Node random;
  7. public Node(int val) {
  8. this.val = val;
  9. this.next = null;
  10. this.random = null;
  11. }
  12. }
  13. */
  14. class Solution {
  15. Map<Node, Node> cachedNode = new HashMap<Node, Node>();
  16. public Node copyRandomList(Node head) {
  17. if (head == null) {
  18. return null;
  19. }
  20. if (!cachedNode.containsKey(head)) {
  21. Node headNew = new Node(head.val);
  22. cachedNode.put(head, headNew);
  23. headNew.next = copyRandomList(head.next);
  24. headNew.random = copyRandomList(head.random);
  25. }
  26. return cachedNode.get(head);
  27. }
  28. }