题目描述:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
方法一:递归
- 从链表的头节点 head 开始递归。
- 每次递归都负责交换一对节点。由 first 和 second 表示要交换的两个节点。
- 下一次递归则是传递的是下一对需要交换的节点。若链表中还有节点,则继续递归。
- 交换了两个节点以后,返回 second,因为它是交换后的新头。
- 在所有节点交换完成以后,我们返回交换后的头,实际上是原始链表的第二个节点。
/**
1. Definition for singly-linked list.
2. public class ListNode {
3. int val;
4. ListNode next;
5. ListNode(int x) { val = x; }
6. }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode first=head;
ListNode second=head.next;
first.next=swapPairs(second.next);
second.next=first;
return second;
}
}
方法二:
- first 和 second 分别遍历偶数节点和奇数节点,即两步看作一步。
- 交换两个节点
- 还需要更新 cur.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) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode cur=dummy;
while(head!=null&&head.next!=null){
ListNode first=head;
ListNode second=head.next;
cur.next=second;
first.next=second.next;
second.next=first;
cur=first;
head=first.next;
}
return dummy.next;
}
}