秋招刷题笔记第三天

秋招刷题笔记第三天

力扣102. 二叉树的层序遍历

在这里插入图片描述

***二叉树层序遍历,本题需要用队列,在此记录队列基本用法


class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
         List<List<Integer>> l = new ArrayList<>();
           if(root==null){
               return l;
           }
            Queue<TreeNode> queue = new ArrayDeque<>();queue.add(root);
            while(!queue.isEmpty()){
             
                 List<Integer> l1=new ArrayList<Integer>();
                int n = queue.size();
                for(int i=0;i<n;i++){
                  TreeNode t= queue.poll();
               
                  l1.add(t.val);
                  if(t.left!=null){
                    queue.add(t.left);
                  }
                  if(t.right!=null){
                    queue.add(t.right);
                  }
                }
                l.add(l1);
            }
            
            return l;
    }
}

力扣19. 删除链表的倒数第 N 个结点

遍历每个节点后面的节点,判断后面的节点个数是否是指定值n,成功则删除此节点

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
              ListNode l = head;
              ListNode m = new ListNode();
              m.next = head;
              ListNode b = m;
              while(l!=null){
                  ListNode temp = l;
                  for(int i=0;i<n;i++){
                      temp = temp.next;
                  }
                
                  if(temp!=null){
                      l = l.next;
                      m = m.next;
                  }else{
                      System.out.print(m.val);
                      m.next = l.next;
                      break;
                  }
              }
              return b.next;
    }
}

力扣61. 旋转链表

在这里插入图片描述
先将链表连成环,在通过规律(n-1)-( k mod n)找到最后一个节点,将链断开

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null){
           return null;
        }
             ListNode l = head;
             int n = 1;
             ListNode t = head;
                while(t.next!=null){
                     t = t.next;
                     n++;
                   }      
                   t.next = l;   
               for(int i=0;i<(n-1)-(k%n);i++){
                    head = head.next;
               }
              ListNode m = head.next;
           
                 head.next = null;   
              return m;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值