给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 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;
}
}