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
Consideration
- Create a dummy head. Let the pointer named pre points to the dummy head.
- To swap two nodes, there are four steps: (1) use a new pointer next points to pre.next.next; (2) make pre.next.next = pre.next; (3)make next.next = pre.next (4) make pre.next = next
- move the pointer pre
==Solution 1: ==
**Time Complexity: O(n) , Space complexity: O(1).
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode pre = dummy;
dummy.next = head;
while(pre.next != null && pre.next.next != null) {
ListNode next = pre.next.next;
pre.next.next = next.next;
next.next = pre.next;
pre.next = next;
pre=pre.next.next;
}
return dummy.next;
}
}