给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
作者亲测可直接运行!!!!!!!!!!!
package com.example.myalgorithm.leetCode;
class LeetCode24 {
// 方法一 递归
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
}
// 方法二 迭代
public static ListNode swapPairs2(ListNode head) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode temp = dummyHead;
while (temp.next != null && temp.next.next != null) {
ListNode node1 = temp.next;
ListNode node2 = temp.next.next;
temp.next = node2;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return dummyHead.next;
}
public static void printListNode(ListNode l) {
while (null != l) {
System.out.println(l.val);
l = l.next;
}
}
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1, new ListNode(4, new ListNode(8, new ListNode(9))));
ListNode resultListNode = swapPairs2(listNode1);
printListNode(resultListNode);
}
}
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}