24.两两交换链表中的节点:
题目链接:. - 力扣(LeetCode)
文章链接:代码随想录
视频链接:帮你把链表细节学清楚! | LeetCode:24. 两两交换链表中的节点_哔哩哔哩_bilibili
思路:利用虚拟头节点交换两个相邻的元素。
具体步骤:
这里while循环条件有两种情况:
链表为偶数时,cur.next ==null 即可视为结束。

链表为奇数时, cur.next.next ==null 即可视为结束

之后,正常进行两两交换即可完成。

具体代码如下:
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyhead = new ListNode(-1); //设置虚拟头节点
dummyhead.next = head;
ListNode cur = dummyhead;
ListNode temp;
ListNode temp2;
while(cur.next!=null && cur.next.next !=null){
temp = cur.next;
temp2 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = temp;
temp.next = temp2;
cur = cur.next.next; //进行下一轮交换之前,cur要走到待交换元素的前一个位置
}
return dummyhead.next;
}
}

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



