Total Accepted: 12160 Total Submissions: 38223
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode pre = newHead;
ListNode cur = pre.next;
while (cur != null && cur.next != null) {
ListNode tmp = cur.next;
cur.next = tmp.next;
pre.next = tmp;
tmp.next = cur;
pre = cur;
cur =cur.next;
}
return newHead.next;
}
}