leetcode 24. Swap Nodes in Pairs

Dear 丶 2023-07-17 15:47 23阅读 0赞

目录

一、问题描述

二、代码实现

1、独立处理第一组节点

2、引入伪头节点使得处理形式统一起来

3、递归版本


https://leetcode.com/problems/swap-nodes-in-pairs/

将单链表每两个节点互换位置。注意不能只改变节点的值,节点必须实实在在地进行交换。

一、问题描述

测试用例:

  1. Example:
  2. Given 1->2->3->4, you should return the list as 2->1->4->3.

需要区分节点个数为偶数和奇数的情况,节点个数为奇数时最后一个节点位置不变。

二、代码实现

1、独立处理第一组节点

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode swapPairs1(ListNode head) {
  11. if (head == null || head.next == null) {
  12. return head;
  13. }
  14. // the size of list is >= 2
  15. // swap the first 2 nodes
  16. ListNode temp = head;
  17. head = head.next;
  18. temp.next = head.next;
  19. head.next = temp;
  20. ListNode pre = temp;
  21. while (pre.next != null && pre.next.next != null) {
  22. ListNode first = pre.next;
  23. ListNode second = pre.next.next;
  24. pre.next = second;
  25. first.next = second.next;
  26. second.next = first;
  27. //pre -> second -> first
  28. pre = pre.next.next;//pre = first;
  29. }
  30. return head;
  31. }
  32. }

2、引入伪头节点使得处理形式统一起来

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode swapPairs2(ListNode head) {
  11. if (head == null || head.next == null) {
  12. return head;
  13. }
  14. ListNode tempHead = new ListNode(-1);
  15. tempHead.next = head;
  16. ListNode pre = tempHead, cur = head;
  17. while (cur != null && cur.next != null) {
  18. ListNode next = cur.next.next;
  19. pre.next = cur.next;
  20. cur.next = next;
  21. pre.next.next = cur;
  22. pre = cur;
  23. cur = next; //cur = cur.next;
  24. }
  25. //cur == null(没有节点了) or cur != null && cur.next == null(只有一个节点)
  26. return tempHead.next;
  27. }
  28. }

3、递归版本

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode swapPairs3(ListNode head) {
  11. //1、出口
  12. if (head == null || head.next == null) {
  13. return head;
  14. }
  15. ListNode newHead = head.next;
  16. head.next = swapPairs(head.next.next);
  17. newHead.next = head;
  18. return newHead;
  19. }
  20. }

参考:

https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11254/Seeking-for-a-better-solution

https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11019/7-8-lines-C%2B%2B-Python-Ruby

https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11030/My-accepted-java-code.-used-recursion.

发表评论

表情:
评论列表 (有 0 条评论,23人围观)

还没有评论,来说两句吧...

相关阅读