LeetCode ---- 24、两两交换链表中的节点
程序员文章站
2022-06-07 10:46:25
...
题目链接
思路:
因为是两两交换,所以需要注意当只剩下一个节点的时候,就不需要交换了。
下面开始使用例子来讲解代码:
原链表如下:
三个指针,cur记录当前节点,curNext记录cur的next节点,curNextNext记录curNext的next节点
开始翻转next指针指向,
前两个翻转:
第3和第4个翻转:
最后拉直链表:
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
ListNode curNext = cur.next;
head = curNext;
while (cur != null && curNext != null) {
ListNode curNextNext = curNext.next;
curNext.next = cur;
ListNode tmp = cur;
cur = curNextNext;
if (curNextNext != null && curNextNext.next != null) {
tmp.next = curNextNext.next;
curNext = curNextNext.next;
} else {
tmp.next = curNextNext;
curNext = null;
}
}
return head;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
上一篇: 从“乾隆盛世”到“鸦片战争”,清朝衰落的根本原因是什么?
下一篇: 妈妈的爱