标签:tno span 链表 style res elf change space air
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
要求把相邻的2个节点两两互换,还必须是换指针而不能是只换值
这里我们用递归的方法来处理,两个指针l1和l2,l1-->l2,我们先把l1和l2换了,然后对l1.next.next继续相同的方法递归下去
/** * 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 res = head.next; head.next = swapPairs(head.next.next); res.next = head; return res; } }
[LeetCode]24. Swap Nodes in Pairs两两交换链表中的节点
标签:tno span 链表 style res elf change space air
原文地址:https://www.cnblogs.com/jchen104/p/10262447.html