24. 两两交换链表中的节点(leetcode每日打卡)

题目描述

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:


输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:

输入:head = []
输出:[]

示例 3:

输入:head = [1]
输出:[1]

思路

保存断掉的结点

题解

/**
 * 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){
            return null;
        }
        ListNode dum=new ListNode(0);
        dum.next=head;
        ListNode cur=dum;
        while(cur.next!=null&&cur.next.next!=null){
            ListNode tmp1=cur.next;
            ListNode tmp3=cur.next.next.next;
            cur.next=cur.next.next;
            cur.next.next=tmp1;
            tmp1.next=tmp3;
            cur=cur.next.next;
        }
        return dum.next;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_60264772/article/details/121328669
今日推荐