【剑指 Offer 06. 从尾到头打印链表】(List<Integer>转int[])

【解题思路】

将链表的值放入list数组中,再将数组逆置。

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
       List<Integer> list = new ArrayList<Integer>();
       ListNode p = head;
       while(p != null)
       {
           list.add(p.val);
           p = p.next;
       }

       int[] ans = list.stream().filter(Integer -> Integer!=null).mapToInt(i->i).toArray();
       for(int i = 0; i < ans.length/2; i++)
       {
           int tmp = ans[i];
           ans[i] = ans[ans.length-i-1];
           ans[ans.length-i-1] = tmp;
       }
       return ans;
    }
}

这里提供两种方法来复制链表: 方法一:使用 HashMap 存储原链表节点和复制节点的对应关系。 ```java public static Node<Integer> copy(Node<Integer> head) { if (head == null) { return null; } Map<Node<Integer>, Node<Integer>> map = new HashMap<>(); Node<Integer> cur = head; // 第一遍遍历,将原链表节点和复制节点的对应关系存入 map 中 while (cur != null) { map.put(cur, new Node<Integer>(cur.value)); cur = cur.next; } cur = head; // 第二遍遍历,设置复制节点的 next 和 random 针 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); } ``` 方法二:在原链表的每个节点后面插入一个复制节点,然后设置复制节点的 random 针和 next 针,最后将复制节点和原节点分开。 ```java public static Node<Integer> copy(Node<Integer> head) { if (head == null) { return null; } Node<Integer> cur = head; // 在每个节点后面插入一个复制节点 while (cur != null) { Node<Integer> copy = new Node<Integer>(cur.value); copy.next = cur.next; cur.next = copy; cur = copy.next; } cur = head; // 设置复制节点的 random 针 while (cur != null) { if (cur.random != null) { cur.next.random = cur.random.next; } cur = cur.next.next; } cur = head; Node<Integer> copyHead = head.next; // 将复制节点和原节点分开 while (cur != null) { Node<Integer> copy = cur.next; cur.next = copy.next; if (copy.next != null) { copy.next = copy.next.next; } cur = cur.next; } // 返回复制链表的头节点 return copyHead; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值