[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.
[Analysis]
这题利用递归可以很简洁地解决,只是思考的过程稍微要绕一下。题目要求不能改变list的值,也就是只能在节点的指针上面下手,观察规律,可以发现需要做的是将两个node互换位置,并且将next设置为下一组交换后的两个节点的第一个,由此构成了一个递归的解法。
[Solution]
public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode node = head.next; head.next = swapPairs(head.next.next); node.next = head; return node; } }
时间: 2024-10-13 11:58:59