- 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
- 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5c6fece7b9fa08fde98cc0beeb85780a.png)
输入:head = [1,2,3,4]
输出:[2,1,4,3]
题解
解法一 递归
- 用
head
表示原始链表的头节点,新的链表的第二个节点,用 newhead
表示新的链表的头节点,原始链表的第二个节点,则原始链表中的其余节点的头节点是 newhead.next
。令head.next=swappairs( newhead.next)
,表示将其余节点进行两两交換,交換后的新的头节点为head
的下ー个节点。然后令newhead.next=head
,即完成了所有节点的交換。最后返回新的链表的头节点 newhead
。
package leetcodePlan.Base;
import leetcodePlan.Base.P0082.ListNode;
public class P0024 {
public static void main(String[] args) {
}
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head ;
}
ListNode newHead = head.next ;
head.next = swapPairs(newHead.next) ;
newHead.next = head ;
return newHead ;
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
}
解法二 迭代
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e1d946b77cb2f0d0c0cd6da861cc6a97.png)
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode temp = dummyHead;
while (temp.next != null && temp.next.next != null) {
ListNode node1 = temp.next;
ListNode node2 = temp.next.next;
temp.next = node2;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return dummyHead.next;
}
}