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:
Given1->2->3->4, you should return the list as2->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) {
if(head == null || head.next == null)
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}

本文提供了一个解决方案,用于在不修改链表节点值的情况下,交换链表中每两个相邻节点的位置。通过递归方法实现,返回交换后的链表头。例如,输入链表1->2->3->4,输出为2->1->4->3。
526

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



