Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
這題就是基本功。
先用dummyHead,
0 -> 1->2->3->4
先把 3那個(gè)點(diǎn)記往, 把2->3斷開规阀。
然后把2指向1调炬,把1指向 3, 把0指向2
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode node = dummy;
dummy.next = head;
while ( true ) {
if (node == null || node.next == null || node.next.next == null) return dummy.next;
ListNode next3 = node.next.next.next;
node.next.next.next = null;
ListNode next = node.next;
ListNode next2 = next.next;
node.next = next2;
next2.next = next;
next.next = next3;
node = next;
}
}