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]
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
解法一:
迭代求解。
/**
* 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
}
}
解法二:
递归求解。
/**
* 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
}
}