Loading

day02

剑指 Offer 06. 从尾到头打印链表

传送门

题意:

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

分析:

java代码实现

class Solution{
    // 节点定义
    // class ListNode{
    //     int val;
    //     ListNode next;

    //     ListNode(int x) {val=x;}
    // }

    private void reverse(ListNode head) {
        // 带头节点的头插法反转链表
        ListNode p = head.next, q=null;
        head.next = null;

        while(p!=null) {
            q = p.next;
            p.next=head.next;
            head.next = p;
            p = q;
        }
    }

    public int[] reversePrint(ListNode head) {

        if (head == null) return new int[0];

        List<Integer> list = new ArrayList<>();
        ListNode dummy = new ListNode(Integer.MAX_VALUE);
        dummy.next = head;
        reverse(dummy);
        ListNode p = dummy.next;

        while(p!=null){
            list.add(p.val);
            p=p.next;
        }

        int arr[] = new int[list.size()];
        for(int i = 0; i < list.size(); i++) arr[i] = list.get(i);
        return arr;

    }
}

剑指 Offer 24. 反转链表

传送门

题意:

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

分析:

头插法反转单链表

java代码实现

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode dummy = new ListNode(-9999);
        dummy.next = head;
        head = dummy;
        ListNode p = head.next, q=null;
        head.next = null;

        while(p!=null) {
            q = p.next;
            p.next=head.next;
            head.next = p;
            p = q;
        }
        return head.next;
    }
}

剑指 Offer 35. 复杂链表的复制

传送门

题意

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

分析

java代码实现

 public Node copyRandomList(Node head) {
        if(head == null) return null;
        Node cur = head;
        Map<Node, Node> map  = new HashMap<>();
        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);
    }
posted @ 2023-04-01 13:18  thiszwinter  阅读(21)  评论(0)    收藏  举报