Difficulty
Medium
Description
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Solution
2ms, 100%
Time Complexity: O(n)
Space Complexity: O(1)
/**
* 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 fakeHead = new ListNode(0);
fakeHead.next = head;
ListNode pre = fakeHead;
while (head != null && head.next != null)
{
ListNode swap = head.next;
head.next = swap.next;
swap.next = head;
pre.next = swap;
pre = head;
head = head.next;
}
return fakeHead.next;
}
}