题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
题解:
方法一:迭代
也是先定义哑结点,然后指向头结点,让后面两个节点交换。然后prev移动,head移动。这种题最多定义三个结点,哑结点,移动结点,移动头结点。
package test;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
// 定义哑结点
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prevNode = dummy;
while ((head != null) && (head.next != null)) {
// 需要交换的两个节点
ListNode firstNode = head;
ListNode secondNode = head.next;
// 头结点指向第二个节点,第一个节点指向第二个节点的下一个节点,第二个节点指向第一个节点
prevNode.next = secondNode;
firstNode.next = secondNode.next;
secondNode.next = firstNode;
// 重新初始化prevNode和head
prevNode = firstNode;
head = firstNode.next; // jump
}
// 返回新的头结点
return dummy.next;
}
}
public class Main {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);//@466
ListNode l2 = new ListNode(2);//@467
ListNode l3 = new ListNode(3);//@468
ListNode l4 = new ListNode(4);//@469
l1.next = l2;
l2.next = l3;
l3.next = l4;
Solution p = new Solution();
ListNode b = p.swapPairs(l1);
while (b != null) {
System.out.print("->" + b.val);
b = b.next;
}
}
}
方法二:递归
这次一定要记住递归三要素,不能改了:
1、终止条件
2、返回值
3、本级递归做什么
以后碰到这个题一定要用递归。
package test;
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;
// }
// //返回值
// head.next = swapPairs(head.next.next);
// head.next.next = head;//这里不能使用两级指针,因为两级之后可能为null,必须定义一个中间指针
// return head.next;
// }
//}
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){//终止条件
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);//返回值
next.next = head;//本级递归做什么
return next;
}
}
public class Main{
public static void main (String []args){
ListNode l1 = new ListNode(1);//@466
ListNode l2 = new ListNode(2);//@467
ListNode l3 = new ListNode(3);//@468
ListNode l4 = new ListNode(4);//@469
l1.next = l2;
l2.next = l3;
l3.next = l4;
Solution p = new Solution();
ListNode b = p.swapPairs(l1);
while (b != null){
System.out.print("->"+b.val);
b = b.next;
}
}
}