/** * 反转链表 递归 */ fun reverseLinkedRe(node: Node?): Node? { if (node?.getNodeNext() == null) { return node } val newNode: Node? = reverseLinkedRe(node.getNodeNext()) node.getNodeNext()?.setNodeNext(node) node.setNodeNext(null) return newNode } /** * 反转链表 非递归 */ fun reverseLinkedDisRe(head: Node?): Node? { if (head == null) return null var node = head val stack: java.util.Stack<Node> = java.util.Stack() while (node != null) { stack.push(Node(node.getNodeValue()!!)) node = node.getNodeNext() } val newNode = stack.pop() node = newNode while (!stack.isEmpty()) { node?.setNodeNext(stack.pop()) node = node?.getNodeNext() } return newNode } /** * 删除倒数第n个结点 */ fun deleteNode(head: Node?, index: Int): Node? { if (head == null) return null if (index == 1) return head.getNodeNext() val emptyNode: Node? = Node(-1) emptyNode?.setNodeNext(head) var start = emptyNode var end = emptyNode for (i in 1 until index) { start = start?.getNodeNext() } while (start != null) { start = start.getNodeNext() end = end?.getNodeNext() } val endNextNext = end?.getNodeNext()?.getNodeNext() end?.setNodeNext(endNextNext) return emptyNode?.getNodeNext() } /** * 合并已排序的两个链表,以递增或递减的顺序输出 */ fun mergeNode(head1: Node2?, head2: Node2?): Node2? { if (head1 == null) return head2 if (head2 == null) return head1 var newHead1 = head1 var newHead2 = head2 var newNode: Node2? = Node2(-1) val pre = newNode while (newHead1 != null && newHead2 != null) { if (newHead1.mValue > newHead2.mValue) { newNode?.mNext = Node2(newHead2.mValue) newHead2 = newHead2.mNext } else { newNode?.mNext = Node2(newHead1.mValue) newHead1 = newHead1.mNext } newNode = newNode?.mNext } newNode?.mNext = newHead1 ?: newHead2 return pre?.mNext } /** * 找到两个链表的交集 */ fun intersectionNode(head1: Node2?, head2: Node2?): Node2? { if (head1 == null || head2 == null) return null var newHead1 = head1 var newHead2 = head2 var newNode: Node2? = Node2(-1) val pre = newNode while (newHead1 != null && newHead2 != null) { if (newHead1.mValue > newHead2.mValue) { newNode?.mNext = Node2(newHead2.mValue) newHead2 = newHead2.mNext } else { newNode?.mNext = Node2(newHead1.mValue) newHead1 = newHead1.mNext } newNode = newNode?.mNext } newNode?.mNext = newHead1 ?: newHead2 return pre?.mNext } /** * 判断链表是否有环,找到环长,环的开始结点 */ fun getNodeLoop(head: Node2?): LoopNode { var p1 = head var p2 = head var isLoop = false var length = 0 while (p1 != null && p2 != null) { p1 = p1.mNext p2 = p2.mNext?.mNext length += 1 if (p1 == p2) { isLoop = true break } } if (!isLoop) { return LoopNode(false, -1, Node2(-1)) } p2 = head while (p1 != null && p2 != null) { p1 = p1.mNext p2 = p2.mNext if (p1 == p2) break } return LoopNode(true, length, p1) }
算法-链表
最新推荐文章于 2024-08-20 10:48:49 发布