141. 环形链表
使用快慢指针,快指针每次走两步,慢指针每次走一步,快指针为null时肯定不存在环,快指针等于慢指针时,肯定存在环。
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head, fast = head;
while (true) {
if (fast.next == null || fast.next.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
}
}
142. 环形链表 II
public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.add(head) == false) {
return head;
}
head = head.next;
}
return null;
}
}
143. 重排链表
class Solution {
public void reorderList(ListNode head) {
if (head == null) {
return;
}
List<ListNode> list = new ArrayList<ListNode>();
ListNode node = head;
while (node != null) {
list.add(node);
node = node.next;
}
int i = 0, j = list.size() - 1;
while (i < j) {
list.get(i).next = list.get(j);
i++;
if (i == j) {
break;
}
list.get(j).next = list.get(i);
j--;
}
list.get(i).next = null;
}
}
class Solution {
public ListNode reverse(ListNode node) {
ListNode dummy = new ListNode(0);
while (node != null) {
ListNode next = node.next;
node.next = dummy.next;
dummy.next = node;
node = next;
}
return dummy.next;
}
public void reorderList(ListNode head) {
if (head == null) {
return;
}
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode newNode = slow.next;
slow.next = null;
newNode = reverse(newNode);
while (newNode != null) {
ListNode temp = newNode.next;
newNode.next = head.next;
head.next = newNode;
head = newNode.next;
newNode = temp;
}
}
}
144. 二叉树的前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode top = stack.poll();
res.add(top.val);
if (top.right != null) {
stack.push(top.right);
}
if (top.left != null) {
stack.push(top.left);
}
}
return res;
}
}
145. 二叉树的后序遍历
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode pre = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.right == null || root.right == pre) {
res.add(root.val);
pre = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return res;
}
}
网友评论