链表反转
双指针法public ListNode ReversalOfLinkedList(ListNode head) { ListNode cur = head; ListNode pre = null; while(cur != null) { ListNode curNext = cur.next; cur.next = pre; pre = cur; cur = curNext; } return pre;}
合并两个有序链表
递归
???public mergeTwoLists(ListNode list1, ListNode list2) { if(list1 == null) { return list2; } else if(list2 == null) { return list1; } else if(list1.val < list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } else { list2.next = mergeTwoLists(list1, list2.next); return list2; }}时间复杂度: O(n+m),其中 n 和 m 分别为两个链表的长度空间复杂度: O(n+m),其中 n 和 m 分别为两个链表的长度。
迭代
public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode newHead = new ListNode(-1); ListNode curNode = newHead; while(list1 != null && list2 != null) { if(list1.val < list2.val) { curNode.next = list1; list1 = list1.next; } else { curNode.next = list2; list2 = list2.next; } curNode = curNode.next; } curNode.next = list1 == null ? list2 : list1; return newHead.next;}时间复杂度:O(n + m),其中 n 和 m 分别为两个链表的长度。空间复杂度: O(1), 只需要常数的空间存放若干变量。
查找链表中间节点
public ListNode findMidNode(ListNode head) { if(head == null || head.next == null) { return head; } ListNode fast = head; ListNode slow = head; while(fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } return slow;}当链表个数为偶数时:正好前后一样多,slow在前半部分的最后一个节点当链表个数为奇数时:slow在中间位置,slow两边一样多
判断链表有环
判断链表有环,并且找到入口节点
public ListNode detectCycle(ListNode head) if(head == null || head.next == null) { return null; } ListNode fast = head; ListNode slow = head; while(fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; // 如果相遇了,则必定有环 if(slow == fast) { slow = head; while(slow != fast) { slow = slow.next; fast = fast.next; } return slow; } } return null;}