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


官方链接

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

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

解法一

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {

        if (head == null || head.next == null) return head;

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode c = dummy;

        while(c.next != null && c.next.next != null) {

            ListNode a = c.next;
            ListNode b = c.next.next;

            a.next = b.next;
            c.next = b;

            b.next = a;

            c = c.next.next;
        }
        return dummy.next;

    }
}
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
      if not head or not head.next:
        return head
      dummy = ListNode(-1)
      dummy.next = head
      c = dummy
      while c.next and c.next.next:
        a, b = c.next, c.next.next
        a.next, c.next = b.next, b
        b.next = a
        c = c.next.next
      return dummy.next

优化

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
      pre, pre.next = self, head
      while pre.next and pre.next.next:
        a = pre.next
        b = a.next
        pre.next, a.next, b.next = b, b.next, a
        pre = a
      return self.next