LeetCode - Algorithms
  • Introduction
  • 1. Two Sum
  • 2. Add Two Numbers
  • 3. Longest Substring Without Repeating Characters
  • 4. Median of Two Sorted Arrays
  • 5. Longest Palindromic Substring
  • 6. ZigZag Conversion
  • 7. Reverse Integer
  • 8. String to Integer (atoi)
  • 9. Palindrome Number
  • 10. Regular Expression Matching
  • 11. Container with Most Water
  • 12. Integer to Roman
  • 13. Roman to Integer
  • 14. Longest Common Prefix
  • 15. 3Sum
  • 16. 3Sum Closest
  • 17. Letter Combinations of a Phone Number
  • 18. 4Sum
  • 19. Remove Nth Node From End of List
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 22. Generate Parentheses
  • 23. Merge k Sorted Lists
  • 24. Swap Nodes in Pairs
  • 25. Reverse Nodes in k-Group
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 29. Divide Two Integers
  • 30. Substring with Concatenation of All Words
  • 31. Next Permutation
  • 32. Longest Valid Parentheses
  • 33. Search in Rotated Sorted Array
  • 34. Search for a Range
  • 35. Search Insert Position
  • 36. Valid Sudoku
  • 37. Sudoku Solver
  • 38. Count and Say
  • 39. Combination Sum
Powered by GitBook
On this page
  • Problem
  • Analysis
  • Code

24. Swap Nodes in Pairs

Problem

Given a linked list, swap every two adjacent nodes and return its head.

For example, Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Related Topics:

Linked List

Analysis

方法一:设置两个指标,遍历的同时进行更换。

方法二:递归。(不符合题意,题目要求只能使用恒定的空间)

Code

遍历:

/**
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int = 0) {
 *     var next: ListNode? = null
 * }
 */
class Solution {

    fun swapPairs(head: ListNode?): ListNode? {

        val h = ListNode(0)
        h.next = head

        var left: ListNode = h
        var right: ListNode? = left.next?.next

        while (right != null) {

            swapPair(left, right)
            left = left.next!!.next!!
            right = left.next?.next
        }

        return h.next
    }

    private fun swapPair(left: ListNode, right: ListNode) {

        left.next?.next = right.next
        right.next = left.next
        left.next = right
    }
}

递归:

/**
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int = 0) {
 *     var next: ListNode? = null
 * }
 */
class Solution {

    fun swapPairs(head: ListNode?): ListNode? {

        val n = head?.next ?: return head

        head.next = swapPairs(n.next)
        n.next = head

        return n
    }
}
Previous23. Merge k Sorted ListsNext25. Reverse Nodes in k-Group

Last updated 6 years ago