2019.7.22

zyb大概是凉凉了 

继续加油啦

============================分割线===========================

Given a binary tree, return the preorder traversal of its nodes' values.先序遍历 输入到list中

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(root == null){
            return list;
        }
        help(root , list);
        return list;
    }
    public void help(TreeNode root , ArrayList<Integer> list){
        list.add(root.val);
        if(root.left != null){
            help(root.left , list);
        }
        if(root.right != null){
           help(root.right , list);
        }
    }
}

Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L nL 1→L n-1→L 2→L n-2→…

You must do this in-place without altering the nodes' values.

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if(head == null){
            return;
        }else{
            if(head.next == null || head.next.next == null){
                return;
            }
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next != null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode after = slow.next;
        slow.next = null;
        ListNode pre = null;
        while(after != null){
              ListNode next = after.next;
              after.next = pre;
              pre = after;
              after = next;
        }
        //反转过链表之后,after已经到了null,此时的pre才是新链表的头节点
           after = pre;
        while(head != null && after != null){
            ListNode headnext = head.next;
            ListNode afternext = after.next;
            head.next = after;
            head = headnext;
            after.next = head;
            after = afternext;
        }
      
    }
}

 

全部评论

相关推荐

07-04 16:00
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 10:56
点赞 评论 收藏
分享
叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务