给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定1->2->3->4
, 你应该返回2->1->4->3
如果只是值的交换,那就是一种潜拷贝,这道题需要结点进行操作,先让1结点连接3结点,然后2结点连接1结点,最后让头节点连接2结点就完成了交换。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
dummy.next = head;
while(cur.next != null && cur.next.next != null){
ListNode next = cur.next;
ListNode nextnext = cur.next.next;
next.next = nextnext.next;
nextnext.next = next;
cur.next = nextnext;
cur = cur.next.next;
}
return dummy.next;
}
}