Swap Nodes in Pairs (M)
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
题意
按顺序将给定的链表中的元素两两交换,但不能更改结点中的值,只能对结点本身进行操作。
思路
问题中包含链表和子结点等概念,且结点需要变动,很容易想到利用递归来解决,直接上代码。
代码实现
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
// 递归边界,当待交换结点数不足2时直接返回
if (head == null || head.next == null) {
return head;
}
ListNode first = head;
ListNode second = first.next;
first.next = swapPairs(second.next);
second.next = first;
return second;
}
}
本文介绍了一种链表操作技巧,即不改变节点值的情况下,通过递归方式实现链表中相邻节点的两两交换。以1->2->3->4为例,经过算法处理后,链表变为2->1->4->3。文章详细解析了递归解决方案,并提供了完整的代码实现。
527

被折叠的 条评论
为什么被折叠?



