首页 > 代码库 > 链表有环判断,快慢指针两种方法/合并链表/删除重复元素/二分递归和while
链表有环判断,快慢指针两种方法/合并链表/删除重复元素/二分递归和while
public static boolean hasCycle(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while (slow != fast) { if (slow.next == null) return false; slow = slow.next; if (fast.next == null) return false; if (fast.next.next == null) return false; fast = fast.next.next; } return true; } public static boolean hasCycle1(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; while (fast.next != null) { if (slow == fast) { return true; } slow = slow.next; if (fast.next.next == null){ return false; } fast = fast.next.next; } return false; }
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); ListNode head1 = l1; ListNode head2 = l2; ListNode resultPoint = result; while (head1 != null && head2 != null) { if (head1.val <= head2.val) { ListNode currNode1 = new ListNode(head1.val); resultPoint.next = currNode1; resultPoint = resultPoint.next; head1 = head1.next; } else { ListNode currNode2 = new ListNode(head2.val); resultPoint.next = currNode2; resultPoint = resultPoint.next; head2 = head2.next; } } if (head1 != null) { resultPoint.next = head1; } if (head2 != null) { resultPoint.next = head2; } return result.next; } }
public static ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode pre = head; ListNode curr = head.next; while (curr != null) { if (curr.val == pre.val) { pre.next = curr.next; } else { pre = pre.next; } curr = curr.next; } return head; }
public static boolean binarySearchDigui(int[] array, int start, int end, int val){ if (start >= end) { return false; } int mid = start + (end - start) / 2; if (val < array[mid]) { return binarySearchDigui(array, start, mid, val); } else if (val > array[mid]){ return binarySearchDigui(array, mid + 1, end, val); } else { return true; } } public static boolean binarySearchWhile(int[] array, int start, int end, int val){ while (start < end) { int mid = start + (end - start) / 2; if (val < array[mid]) { end = mid; } else if (val > array[mid]){ start = mid + 1; } else { return true; } } return false; }
链表有环判断,快慢指针两种方法/合并链表/删除重复元素/二分递归和while
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。