查询 O(n) 增删改O(1) image.png


21. 合并有序链表

image.png

  1. class Solution {
  2. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  3. if (l1 == null) return l2;
  4. if (l2 == null) return l1;
  5. if (l1.val < l2.val) {
  6. l1.next = mergeTwoLists(l1.next, l2);
  7. return l1;
  8. } else {
  9. l2.next = mergeTwoLists(l1, l2.next);
  10. return l2;
  11. }
  12. }
  13. }

24. 两两交换链表中的节点

image.png

  1. class Solution {
  2. public ListNode swapPairs(ListNode head) {
  3. if (head == null || head.next == null)
  4. return head;
  5. ListNode n = head.next;
  6. head.next = swapPairs(n.next);
  7. n.next = head;
  8. return n;
  9. }
  10. }

25. K个一组翻转链表

image.png

  1. class Solution {
  2. //递归
  3. public ListNode reverseKGroup(ListNode head, int k) {
  4. ListNode curr = head;
  5. int count = 0;
  6. while (curr != null && count != k) {
  7. curr = curr.next;
  8. count++;
  9. }
  10. if (count == k) {
  11. curr = reverseKGroup(curr, k);
  12. while (count-- > 0) {
  13. ListNode tmp = head.next;
  14. head.next = curr;
  15. curr = head;
  16. head = tmp;
  17. }
  18. head = curr;
  19. }
  20. return head;
  21. }
  22. }

141. 环形链表

image.png

  1. public class Solution {
  2. public boolean hasCycle(ListNode head) {
  3. if (head == null || head.next == null)
  4. return false;
  5. ListNode low = head;
  6. ListNode fast = head;
  7. while (fast.next != null && fast.next.next != null) {
  8. low = low.next;
  9. fast = fast.next.next;
  10. if (low == fast) return true;
  11. }
  12. return false;
  13. }
  14. }

142. 环形链表二

image.png

  1. public class Solution {
  2. public ListNode detectCycle(ListNode head) {
  3. Set<ListNode> set = new HashSet<>();
  4. while (head != null) {
  5. if (set.contains(head)) return head;
  6. set.add(head);
  7. head = head.next;
  8. }
  9. return null;
  10. }
  11. }

206. 反转链表

image.png

  1. class Solution {
  2. public ListNode reverseList(ListNode head) {
  3. ListNode newHead = null;
  4. while (head != null) {
  5. ListNode next = head.next;
  6. head.next = newHead;
  7. newHead = head;
  8. head = next;
  9. }
  10. return newHead;
  11. }
  12. }