halfrost / LeetCode-Go

✅ Solutions to LeetCode by Go, 100% test coverage, runtime beats 100% / LeetCode 题解
https://books.halfrost.com/leetcode
MIT License
32.76k stars 5.68k forks source link

Use a concise solution for problem 24 swap nodes in pairs #140

Closed hanlins closed 3 years ago

hanlins commented 3 years ago

Signed-off-by: Hanlin Shi shihanlin9@gmail.com

The initial state of the chain is pt -> 1 -> 2 -> 3, the nodes are represented by pt, pt.Next, pt.Next.Next and pt.Next.Next.Next. After the swap, the chain is pt -> 2 -> 1 -> 3, and pt points to 1. We can easily update the variables, point to the new Next in one line.