0
点赞
收藏
分享

微信扫一扫

数据结构与算法【LeetCode-Offer】:2.6链表—24. 两两交换链表中的节点


题目描述

​​题目链接​​

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

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

数据结构与算法【LeetCode-Offer】:2.6链表—24. 两两交换链表中的节点_leetcode

解题思路

数据结构与算法【LeetCode-Offer】:2.6链表—24. 两两交换链表中的节点_数据结构_02

package com.kami.leetcode.list_study;

import com.kami.leetcode.list_study.listNode.ListNode;

/**
* @Description: TODO
* @author: scott
* @date: 2021年12月20日 9:30
*/
public class Solution_24 {
public ListNode swapPairs(ListNode head){
if(head == null || head.next == null){
return head;
}

//添加一个虚拟头节点
ListNode dummy = new ListNode(0);
dummy.next = head;

// cur 是两两相邻节点中第一个节点的前驱节点
ListNode cur = dummy;
while (cur != null && cur.next != null && cur.next.next != null){
//两两相邻的第一个节点
ListNode first = cur.next;
// 两两相邻的第二个节点
ListNode second = cur.next.next;
ListNode successor = second.next;

cur.next = second;
second.next = first;
first.next = successor;

// cur 向右移动两位,进入下一轮交换
cur = cur.next.next;
}

return dummy.next;
}
}


举报

相关推荐

0 条评论