题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
代码实现
package com.leetcode.链表;
/**
* Author:markusZhang
* VM Args:
* Date:Create in 2020/2/2 15:23
*/
public class 两两交换链表中的节点 {
static class ListNode{
int val;
ListNode next;
public ListNode(){}
public ListNode(int val){
this.val = val;
}
//迭代方式
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode prevNode = new ListNode(-1);
prevNode.next = head;
ListNode pNode = prevNode;
while(head!=null && head.next!=null){
ListNode firstNode = head;
ListNode secondNode = head.next;
//交换
pNode.next = secondNode;
firstNode.next = secondNode.next;
secondNode.next = firstNode;
//更新前驱结点
pNode.next = secondNode;
//更新需要交换的头节点
head = pNode.next;
}
return prevNode.next;
}
//递归方式
public ListNode swapPairs1(ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode firstNode = head;
ListNode secondNode = head.next;
firstNode.next = swapPairs1(secondNode.next);
secondNode.next = firstNode;
return secondNode;
}
}
}