Problem: Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example:
Input: head = [1,2,3,4] Output: [2,1,4,3]
Input: head = [] Output: []
Input: head = [1] Output: [1]
Approach: Not much to explain as it is very much a straight forward problem to solve. You can understand the approach by just looking at the implementation.
Implementation in C#:
public ListNode SwapPairs(ListNode head)
{
if (head?.next == null)
{
return head;
}
ListNode node1 = head;
ListNode node2 = head.next;
head = head.next;
ListNode prev = null;
while(node1 != null && node2 != null)
{
ListNode next = node2.next;
node2.next = node1;
node1.next = next;
if (prev != null)
{
prev.next = node2;
}
prev = node1;
node1 = next;
node2 = node1?.next;
}
return head;
}
Complexity: O(n)
No comments:
Post a Comment