Leetcode 24.两两交换链表中的节点
题目要求
- 给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:

输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例2:
输入:head = []
输出:[]
示例3:
输入:head = [1]
输出:[1]
提交
双temp实现交换
之所以要设置虚拟头结点,一是为了方便操作链表,而是为了最后的返回值
如果不设置dumyhead,而是直接让cur.next = head,那么最后会无法返回链表的头
关键步骤如下图所示:




1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class Solution { public ListNode swapPairs(ListNode head) { ListNode dumyhead = new ListNode(-1); dumyhead.next = head; ListNode cur = dumyhead; ListNode temp1 = null; ListNode temp2 = null; while(cur.next != null && cur.next.next != null){ temp1 = cur.next; temp2 = cur.next.next.next; cur.next = cur.next.next; cur.next.next = temp1; temp1.next = temp2; cur = cur.next.next; } return dumyhead.next; } }
|