【坚持】Leetcode《剑指offer》学习计划Day02

剑指 Offer 06. 从尾到头打印链表
【坚持】Leetcode《剑指offer》学习计划Day02_第1张图片

class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<ListNode> s = new Stack<ListNode>();
        while(head!=null){
            s.push(head);
            head = head.next;
        }
        int size = s.size();
        int []arr = new int[size];
        for(int i = 0;i < size;i++){
            arr[i] = s.pop().val;
        }
        return arr;
    }
}

点评:
注意审题,这个题的核心意思是要得到逆序的值,而不是要改变别人的原始数据结构错解:ListNode jump = head; while(jump!=null){ ListNode next = jump.next; jump.next.next =jump; jump = next; }
口诀:“想逆序就用栈”

剑指 Offer 24. 反转链表

【坚持】Leetcode《剑指offer》学习计划Day02_第2张图片

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode jump = head;
        ListNode pre = null;
        while(jump!=null){
            ListNode next = jump.next;
            jump.next = pre; 
            pre = jump;
            jump = next;
        }
        return pre;
    }
}

点评:这个才是真正的反转链表啊!改变了其数据结构,靠的是一个蠕动模式
口诀:蠕动反转法

剑指 Offer 35. 复杂链表的复制
【坚持】Leetcode《剑指offer》学习计划Day02_第3张图片

class Solution {
    public Node copyRandomList(Node head) {
        HashMap<Node,Node> map = new HashMap<Node,Node>();
        Node cur = head;
        while(cur!=null){
            map.put(cur,new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        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);
    }
}

这只是一种简单做法,还有进阶做法:


class Solution {
    public Node copyRandomList(Node head) {
       if(head == null){
           return null;
       }
       Node cur = head;
       Node next = null;
       while(cur!=null){
           next = cur.next;
           Node temp =  new Node(cur.val);
           cur.next = temp;
           temp.next = next;
           cur = next;
       }
       cur = head;
       Node curCopy = null;
       while(cur!=null){
           next = cur.next.next;
           curCopy = cur.next;
           curCopy.random = cur.random!=null?cur.random.next:null;
            cur = next;
       }
        Node res = head.next;
        cur = head;
        while(cur!=null){
            next = cur.next.next;
            curCopy = cur.next;
            cur.next = next;
            curCopy.next = next!=null?next.next:null;
            cur = next;
        }
        return res;  
    }
}

三个过程:复制 + 构建关系 + 分离

你可能感兴趣的:(剑指offer基础版,leetcode,链表,数据结构)