剑指Offer —— 算法题(九)

这个专栏 我将分享每日做的算法题的解题思路 秋招加油!
这是第九天 !!

027 回文链表

题目
在这里插入图片描述
AC代码

class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while(head != null){
            list.add(head.val);
            head = head.next;
        }
        int left = 0,right = list.size()-1;
        while(left <= right){
            if(list.get(left) != list.get(right)){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

这道题通过list存储数值,然后在list上判断即可。

028 展平多级双向链表

题目
在这里插入图片描述
AC代码

class Solution {
    List<Node> list = new ArrayList<>();

    public Node flatten(Node head) {
        dfs(head);
        for(int i=0;i<list.size()-1;i++){
            Node pre = list.get(i);
            Node cur = list.get(i+1);
            pre.next = cur;
            cur.prev = pre;
            pre.child = null;
        }
        return head;
    }

    public void dfs(Node head){
        if(head == null) return;
        list.add(head);
        dfs(head.child);
        dfs(head.next);
    }
}

典型的DFS问题,需要先遍历child节点,再遍历next节点。

029 排序的循环链表

题目
在这里插入图片描述
AC代码

class Solution {
    public Node insert(Node head, int insertVal) {
        Node cur = null;
       Node next = null;
       Node realHead = null;
       if(head == null){
           head = new Node(insertVal);
           head.next = head;
           return head;
       }
       cur = head;
       next = head.next;
        while(cur.val <= next.val){
            cur = cur.next;
            next = next.next;
            if(cur == head) break;
        }
        realHead = next;

        while(next.val < insertVal){
            cur = next;
            next = next.next;
            if(next == realHead)break;
        }
        cur.next = new Node(insertVal);
        cur = cur.next;
        cur.next = next;
        return head;
    }
}

找到真正的头节点,也就是最小的节点,然后从这个节点开始遍历,找到插入的位置,插入节点即可。

成功需要时间
不能一蹴而就
努力工作
坚持不懈
保持耐心

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值