给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
迭代做法
解题思路
- 利用一个dummyNode结点的next来指向head结点,方便之后的返回。同时还有curr结点指向dummyNode结点。
- 当链表中还有构成一对的元素可以进行交换的时候,进行循环
- nextNode和nextNextNode结点分别记录curr的next结点和next.next结点
- nextNode的next指向nextNextNode的next结点
- nextNextNode的next指向nextNode
- curr的next指向nextNextNode
- curr进行移动,curr移动到curr的next.next上面
- 返回dummyNode的next结点,即交换完成之后的结果链表的头结点
package LT;/*
* Created by lizeyu on 2020/9/12 14:45
*/
public class SwapTwoNodes {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode swapPairs(ListNode head) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode curr = dummyNode;
while (curr.next != null && curr.next.next != null) {
ListNode nextNode = curr.next;
ListNode nextNextNode = curr.next.next;
nextNode.next = nextNextNode.next;
nextNextNode.next = nextNode;
curr.next = nextNextNode;
curr = curr.next.next;
}
return dummyNode.next;
}
}
时间复杂度:O(N),空间复杂度:O(1)
递归的做法
递归的三部曲
- 递归的终止条件:本体是当head为null或者head的next结点为null时终止递归,返回head
- 返回值:这里应该返回给上一级递归的是完成交换的子链表的头结点,本题是完成交换之后的SecondNode结点
- 每一级递归的任务:交换两个结点,即每一对需要交换的元素中的FirstNode的next指向交换完成的后续链表的头结点。SecondNode的next指向FirstNode
package LT;/*
* Created by lizeyu on 2020/9/12 15:52
*/
public class SwapTwoNodes2 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode FirstNode = head;
ListNode SecondNode = head.next;
FirstNode.next = swapPairs(SecondNode.next);
SecondNode.next = FirstNode;
return SecondNode;
}
}
** 时间复杂度:O(N),空间复杂度:O(N)**