0
点赞
收藏
分享

微信扫一扫

LeetCode24 两两交换链表中的节点

小贴贴纸happy 2022-03-12 阅读 21
算法

题目

在这里插入图片描述

解题思路

画图模拟
在这里插入图片描述

(上图是对代码随想录的图进行修改)

代码

/**
 * 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) {
        if(head==null || head.next==null)return head;
        ListNode dummy = new ListNode(); //虚拟节点
        ListNode pre = dummy;
        ListNode cur = head;

        while(cur!=null && cur.next!=null){
            pre.next = cur.next;
            ListNode temp = cur.next.next; 
            cur.next.next = cur;
            cur.next = temp;
            pre = cur;
            cur = cur.next;
        
        }
        return dummy.next;
    }
}
举报

相关推荐

0 条评论