给一个链表,两两交换其中的节点,然后返回交换后的链表。
给出 1->2->3->4
, 你应该返回的链表是 2->1->4->3
。
本题只要循环判断后两个节点不为空的情况下,将后面这两个元素进行交换即可,最重要的是,交换的时候,要记得保留原数据,以便拼接起来链表,谨防数据丢失。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a ListNode
*/
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while (head.next != null && head.next.next != null) {
ListNode n1 = head.next;
ListNode n2 = head.next.next;
head.next = n2;
n1.next = n2.next;
n2.next = n1;
head = n1;
}
return dummy.next;
}
}