链表反转

  1. 双指针法
  2. public ListNode ReversalOfLinkedList(ListNode head) {
  3. ListNode cur = head;
  4. ListNode pre = null;
  5. while(cur != null) {
  6. ListNode curNext = cur.next;
  7. cur.next = pre;
  8. pre = cur;
  9. cur = curNext;
  10. }
  11. return pre;
  12. }

合并两个有序链表

递归

  1. ???
  2. public mergeTwoLists(ListNode list1, ListNode list2) {
  3. if(list1 == null) {
  4. return list2;
  5. } else if(list2 == null) {
  6. return list1;
  7. } else if(list1.val < list2.val) {
  8. list1.next = mergeTwoLists(list1.next, list2);
  9. return list1;
  10. } else {
  11. list2.next = mergeTwoLists(list1, list2.next);
  12. return list2;
  13. }
  14. }
  15. 时间复杂度: O(n+m),其中 n m 分别为两个链表的长度
  16. 空间复杂度: O(n+m),其中 n m 分别为两个链表的长度。

迭代

  1. public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
  2. ListNode newHead = new ListNode(-1);
  3. ListNode curNode = newHead;
  4. while(list1 != null && list2 != null) {
  5. if(list1.val < list2.val) {
  6. curNode.next = list1;
  7. list1 = list1.next;
  8. } else {
  9. curNode.next = list2;
  10. list2 = list2.next;
  11. }
  12. curNode = curNode.next;
  13. }
  14. curNode.next = list1 == null ? list2 : list1;
  15. return newHead.next;
  16. }
  17. 时间复杂度:O(n + m),其中 n m 分别为两个链表的长度。
  18. 空间复杂度: O(1), 只需要常数的空间存放若干变量。

查找链表中间节点

  1. public ListNode findMidNode(ListNode head) {
  2. if(head == null || head.next == null) {
  3. return head;
  4. }
  5. ListNode fast = head;
  6. ListNode slow = head;
  7. while(fast.next != null && fast.next.next != null) {
  8. fast = fast.next.next;
  9. slow = slow.next;
  10. }
  11. return slow;
  12. }
  13. 当链表个数为偶数时:正好前后一样多,slow在前半部分的最后一个节点
  14. 当链表个数为奇数时:slow在中间位置,slow两边一样多

判断链表有环

判断链表有环,并且找到入口节点

  1. public ListNode detectCycle(ListNode head)
  2. if(head == null || head.next == null) {
  3. return null;
  4. }
  5. ListNode fast = head;
  6. ListNode slow = head;
  7. while(fast.next != null && fast.next.next != null) {
  8. fast = fast.next.next;
  9. slow = slow.next;
  10. // 如果相遇了,则必定有环
  11. if(slow == fast) {
  12. slow = head;
  13. while(slow != fast) {
  14. slow = slow.next;
  15. fast = fast.next;
  16. }
  17. return slow;
  18. }
  19. }
  20. return null;
  21. }