给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
示例:
给定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; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {//不设置dummyHead得到的结果是2,4 17、20行
ListNode dummyHead=new ListNode(0);
dummyHead.next=head;
head=dummyHead;
while(head.next!=null&&head.next.next!=null){
ListNode node1=head.next;
ListNode node2=head.next.next;
head.next=node2;
node1.next=node2.next;
node2.next=node1;
head=node1;
}
return dummyHead.next;
}
}