标签:linked fir ini second tno his pair sha head
递归法,假设后续链表已经完成交换,此时只需要对前两个节点进行交换,然后再连接上后续已交换的链表即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode SwapPairs(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode next = head.next.next;
ListNode first = head, second = head.next;
second.next = first;
first.next = SwapPairs(next);
return second;
}
}
[LeetCode题解]24. 两两交换链表中的节点 | 递归
标签:linked fir ini second tno his pair sha head
原文地址:https://www.cnblogs.com/liang24/p/14016027.html