问题描述
- Given a linked list, swap every two adjacent nodes and return its head.
- Example
Given 1->2->3->4, you should return the list as 2->1->4->3.
- Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list’s nodes, only nodes itself may be changed.
- 地址
问题分析
- 该题是实现每两个节点交换一下,不能通过改变节点的 val ,只能通过改变指针的方式来改变。并要求空间复杂度为 O(1)
- 可以先从小问题分析,如果是
1 -> 2 -> 3
想要变成2 -> 1 -> 3
那么可以先用一个临时变量 temp 保存 3节点,然后将 2 的next 指向 1,然后将 1的next 指向 3即可。但是要注意的是,因为我们改变了头结点,可能会导致无法找到调整后头结点的情况,所以必须引入一个 dummy 指针,用作 pre指针,2连在它的后面即可。以此类推,直到当前节点为空,或者当前节点下一节点为空。
代码实现
- dummy 法
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
//初始化 preNode 以及 curNode
ListNode preNode = dummy;
ListNode curNode = head;
while (curNode != null && curNode.next != null) {
ListNode nextNode = curNode.next;
preNode.next = nextNode;
ListNode temp = nextNode.next;
nextNode.next = curNode;
curNode.next = temp;
preNode = curNode;
curNode = temp;
}
return dummy.next;
}
- 递归法(虽然不满足本题要求 ,但写起来还是很优雅的)
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
ListNode resList = swapPairs(newHead.next);
newHead.next = head;
head.next = resList;
return newHead;
}