剑指offer计划2(链表)---java

1.1、题目1

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

1.2、解法

本题 我使用的是简单获取链表长度并创建数组,同时从数组尾部向前赋值。

1.3、代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        int n = getsize(head);
        int []res= new int[n];
        for(int i=n-1;i>=0;i--){
            res[i]=head.val;
            head=head.next;
        }
        return res;
    }
    public int getsize(ListNode head){
        ListNode i = head;
        int res =0;
        while(i!=null){
            res++;
            i=i.next;
        }
        return res;
    }
}

2.1、题目2

剑指 Offer 24. 反转链表

2.2、解法

设置一个三个结点,不断递进。

中间的next为前个结点,中间结点变成下个结点,前个结点变成中间结点。

2.3、代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode l =head;
        ListNode pre = null;
        while(l!=null){
            ListNode next = l.next;
            l.next= pre;
            pre=l;
            l=next;
        }
        return pre;

    }
}

3.1、题目3

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

3.2、解法

这题回溯加哈希表,定义一个哈希表存结点,
下面是回溯法标准模板,判断是否为空,则返回空
若是哈希表不包含该结点,则放入哈希表中,该复制结点的next和random重复以上操作。

(复制官方答案的)~~~

3.3、代码

class Solution {
    Map<Node, Node> cachedNode = new HashMap<Node, Node>();

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        if (!cachedNode.containsKey(head)) {
            Node headNew = new Node(head.val);
            cachedNode.put(head, headNew);
            headNew.next = copyRandomList(head.next);
            headNew.random = copyRandomList(head.random);
        }
        return cachedNode.get(head);
    }
}
posted @ 2021-09-02 09:10  程序员khaos  阅读(82)  评论(0编辑  收藏  举报