算法:成对交换链表节点24. Swap Nodes in Pairs

Posted 架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:成对交换链表节点24. Swap Nodes in Pairs相关的知识,希望对你有一定的参考价值。

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

1. 尾递归解法

尾递归的思路:只要处理前面的逻辑,那么head.next = swapPairs(head.next.next); 就会用同样的逻辑处理。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }
}
  1. 遍历解法
    遍历的解法:用快慢两个指针比较好理解。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        while (pre.next != null && pre.next.next != null) {
            ListNode slow = pre.next, fast = pre.next.next;
            slow.next = fast.next;
            pre.next = fast;
            fast.next = slow;
            pre = slow;
        }
        
        return dummy.next;
    }
}

参考

https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11046/My-simple-JAVA-solution-for-share

以上是关于算法:成对交换链表节点24. Swap Nodes in Pairs的主要内容,如果未能解决你的问题,请参考以下文章

leetcode#24 Swap Nodes in Pairs

leetcode 24. 两两交换链表中的节点(Swap Nodes in Pairs)

[LeetCode] 24. Swap Nodes in Pairs

LeetCode 24. 两两交换链表中的节点 Swap Nodes in Pairs (Medium)

[leetcode]24. Swap Nodes in Pairs交换链表的节点

Leetcode 24题 两两交换链表中的节点(Swap Nodes in Pairs))Java语言求解