LC141. 环形链表
核心思想在于:双指针思想,初始化指针以后进入while循环去遍历,假如快慢指针相遇说明有环,如果没相遇说明没环
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(slow == fast)
return true;
}
return false;
}
}
LC21. 合并两个有序链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}else if(l2 == null){
return l1;
}else if(l1.val < l2.val){
l1.next = mergeTwoLists(l2,l1.next);
return l1;
}else{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
}
LC102. 二叉树的层序遍历
核心思想在于:
主要考察的是对树的一个理解同时层级遍历通过队列去保存树的节点,循环当中通过队列的长度判断达到一个层级遍历的效果
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> item = new LinkedList();
int len = queue.size();
while(len > 0){
TreeNode node = queue.poll();
item.add(node.val);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
len--;
}
res.add(item);
}
return res;
}
}