LeetCode24. 两两交换链表中的节点(图解、简单易懂)

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。

在这里插入图片描述

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs

分析:根据题目要求,得知我们不可以只是简单是对节点的值进行交换,而是需要更改指针的指向,首先新建一个虚拟头节点,简化代码。

   ListNode Vhead = new ListNode(-1);
   Vhead.next = head;

然后通过节点one,two,three来进行指针交换,具体细节看下图:
在这里插入图片描述通过三个步骤的交换,循环进行就可以得出结果,全部代码如下:

/**
 * 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 Vhead = new ListNode(-1);
        Vhead.next = head;
        ListNode one = Vhead;
        while(one.next != null && one.next.next != null){
            ListNode two = one.next;
            ListNode three = one.next.next;
            one.next = three;
            two.next = three.next;
            three.next = two;
            one = two;
        }
        return Vhead.next;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值