思路:两次遍历。第一次遍历获取链表节点个数;第二次遍历从后往前存储数据
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);
}
}
本文介绍了三种链表操作的解决方案:一是从尾到头打印链表,通过两次遍历来实现;二是反转链表,使用头插法;三是复杂链表的复制,利用哈希表辅助完成节点复制和随机指针的设置。
265

被折叠的 条评论
为什么被折叠?



