代码随想录打卡day4

原文链接

Problem: 24. 两两交换链表中的节点

思路

画图理解

解题方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cCH6R09g-1679156501053)(https://pic.leetcode.cn/1679149347-broYyK-%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230318222218.jpg)]

复杂度

  • 时间复杂度:

O ( n ) O(n) O(n)

  • 空间复杂度:

O ( 1 ) O(1) O(1)

Code


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
//迭代法
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummyHead = new ListNode(-1,head);
        ListNode cur = dummyHead;
        while(cur.next != null && cur.next.next != null){
            ListNode firstNode = cur.next;
            ListNode temp = cur.next.next.next;
            cur.next = cur.next.next;
            cur.next.next = firstNode;
            firstNode.next = temp;
            cur = cur.next.next;
        }
        return dummyHead.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值