题目描述
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
给你一个链表,交换相邻的两个链表解题思路
- 交换相邻两个链表节点,并将交换的尾节点记录;
- 将上次的尾节点指向本次交换后的头节点;
- 重复上述步骤;
以上需要注意如果节点个数为奇数的情况。
代码
public ListNode swapPairs(ListNode head) {
ListNode node = head, result = head;
ListNode firstNode = head;
ListNode secondNode = head;
ListNode lastNode = head;
while (node != null) {
firstNode = node;
secondNode = node.next;
if (secondNode == null) {
//考虑节点个数为奇数的情况
secondNode = node;
} else {
firstNode.next = secondNode.next;
secondNode.next = firstNode;
}
if (firstNode == head) {
//第一次交换时,记录最终交换完的头节点
result = secondNode;
} else {
//上一次交换的尾节点指向本次交换完的头节点
lastNode.next = secondNode;
}
lastNode = firstNode;
node = firstNode.next;
}
return result;
}