给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
作者亲测可直接运行!!!!!!!!!!!
class Solution {
public static ListNode swapPairs(ListNode head) {
if (head == null) return null;
ListNode p1 = head;
ListNode p2 = head.next;
if (p2 == null) return p1;
ListNode newHead = p2;
ListNode pre = null;
while (p1 != null && p2 != null) {
p1.next = p2.next;
p2.next = p1;
if (pre != null) pre.next = p2;
pre = p1;
p1 = p1.next;
if (p1 != null) {
p2 = p1.next;
}
}
return newHead;
}
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 = swapPairs(listNode1);
printListNode(resultListNode);
}
}
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}