思路:两次遍历。第一次遍历获取链表节点个数;第二次遍历从后往前存储数据
class Solution {
public int[] reversePrint(ListNode head) {
int len = 0;
ListNode node = head;
while(node!=null){
len++;
node = node.next;
}
int res[] = new int[len];
while (head!=null){
res[--len] = head.val;
head = head.next;
}
return res;
}
}
思路:反转链表应该想到用头插法。想清楚插入节点时的操作顺序。
class Solution {
public ListNode reverseList(ListNode head) {
if (head==null|| head.next==null){
return head;
}
ListNode cur = head;
ListNode next;
ListNode new_head = new ListNode(0);
while (cur!=null){
next = cur.next;
cur.next = new_head.next;
new_head.next = cur;
cur = next;
}
return new_head.next;
}
}
思路:这个有点难,用到了哈希表。复习时再看看
class Solution {
public Node copyRandomList(Node head) {
if (head == null)
return head;
Map<Node,Node> map = new HashMap<>();
for (Node cur = head;cur!=null;cur=cur.next){
map.put(cur,new Node(cur.val));
}
for (Node cur=head;cur!=null;cur=cur.next){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
}
return map.get(head);
}
}