23剑指Offer_23_链表中环的入口结点
public class 剑指Offer_23_链表中环的入口结点 {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null || head.next.next == null) return null;
ListNode slow = head.next;
ListNode fast = head.next.next;
while (slow != fast) {
if (fast.next == null || fast.next.next == null) {
return null;
}
slow = slow.next;
fast = fast.next.next;
}
fast = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
24 剑指Offer_24_反转链表
public class 剑指Offer_24_反转链表 {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = null;
while (head != null) {
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
25 剑指Offer_25_合并两个排序的链表
public class 剑指Offer_25_合并两个排序的链表 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode dummyHead = new ListNode(0);
ListNode dummyTail = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val >= l2.val) {
dummyTail.next = l2;
l2 = l2.next;
} else {
dummyTail.next = l1;
l1 = l1.next;
}
dummyTail = dummyTail.next;
}
if (l1 != null) {
dummyTail.next = l1;
}
if (l2 != null) {
dummyTail.next = l2;
}
return dummyHead.next;
}
}
26 剑指Offer_26_树的子结构
public class 剑指Offer_26_树的子结构 {
public boolean isSubStructure(TreeNode A, TreeNode B) {
if (A == null || B == null) return false;
return recur(A,B)||isSubStructure(A.left,B)||isSubStructure(A.right,B);
}
private boolean recur(TreeNode A,TreeNode B){
if (B == null) return true;
if (A == null || A.val != B.val) return false;
return recur(A.left, B.left)&&recur(A.right,B.right);
}
}