一 题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
二 解题思路:
将遍历的指针位置后一个节点,及下下个节点记录下来,然后将下个节点的next指向当前指针,当前指针的next指向下下个节点;
将当前指针位置存到一个节点遍历中比如pre,这个pre在下次做交换处理的时候,修改其next指向
如果当前指针为head那么将链表的head赋值为指针的下一个节点。
三 代码实现
class Solution {
public ListNode swapPairs(ListNode head) {
//处理特殊情况
if (head == null || head.next == null){
return head;
}
//记录遍历指针
ListNode cur = head;
//指针下次跳转的位置
ListNode nextCur = null;
//指针的下一个节点
ListNode next = null;
//上一次反转的尾节点
ListNode pre = null;
while (cur != null && cur.next != null){
//把当前指针的下下个节点记录下来
nextCur = cur.next.next;
next = cur.next;
next.next = cur;
cur.next = nextCur;
if (cur == head){
head = next;
}
if (pre != null){
pre.next = next;
}
pre = cur;
cur = nextCur;
}
return head;
}
}