代码随想录算法训练营第4天| 24.两两交换链表中的节点 | 19 删除链表的倒数第N个节点 | 面试题02.07.链表相交 | 142.环形链表

 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值