Leetcode.com/problems/sw…
Discuss:www.cnblogs.com/grandyang/p…
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]
Copy the code
Example 2:
Input: head = []
Output: []
Copy the code
Example 3:
Input: head = [1]
Output: [1]
Copy the code
Constraints:
The number of nodes in the list is in the range [0, 100]. 0 <= Node.val <= 100
Solution a:
Iterative solution.
/** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun swapPairs(head: ListNode?) : ListNode? { if (head? .next == null) { return head } val dummy: ListNode? = ListNode(-1) var pre = dummy dummy? .next = head while (pre? .next ! = null && pre.next? .next ! = null) { val a = pre.next val b = a? .next val c = b? .next pre.next = b b? .next = a a? .next = c pre = a } return dummy? .next } }Copy the code
Method 2:
Recursively.
/** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun swapPairs(head: ListNode?) : ListNode? { if (head? .next == null) { return head } val listNode = head.next head.next = swapPairs(head.next? .next) listNode? .next = head return listNode } }Copy the code