0% completed
Problem 5: Swap Nodes in Pairs (medium)
Problem Statement
Given a singly linked list, swap every two adjacent nodes and return the head of the modified list.
If the total number of nodes in the list is odd, the last node remains in place. Every node in the linked list contains a single integer value.
Examples
-
Input:
[1, 2, 3, 4]
Output:[2, 1, 4, 3]
Justification: Pairs (1,2) and (3,4) are swapped. -
Input:
[7, 8, 9, 10, 11]
Output:[8, 7, 10, 9, 11]
Justification: Pairs (7,8) and (9,10) are swapped. 11 remains in its place as it has no adjacent node to swap with.
.....
.....
.....
gabbygabbylexy
· a year ago
public class Solution { public ListNode swapPairs(ListNode head) { // TODO: Write your code here if (head == null || head.Next == null) return head; var dummy = new ListNode(0); dummy.Next = head; var current = dummy; while (current.Next != null && current.Next.Next != null) { var first = current.Next; var second = current.Next.Next; current.Next = second; first.Next = second.Next; second.Next = first; current = first; } return dummy.Next; } }
Farouk Elabady
· 2 years ago
In this solution I swapped the values instead of the references which is simpler , It may not be the correct approach to get familiar with LinkedList
Solution { public ListNode swapPairs(ListNode head) { // TODO: Write your code hereu ListNode current = head; while(current != null && current.next != null) { int t = current.val; current.val = current.next.val; current.next.val = t; current = current.next.next; } return head; } }
Davide Pugliese
· 2 years ago
// class ListNode { // int val; // ListNode next; // ListNode() {} // ListNode(int val) { this.val = val; } // ListNode(int val, ListNode next) { this.val = val; this.next = next; } // } class Solution { public ListNode swapPairs(ListNode head) { ListNode p = head; ListNode dummy = new ListNode(-1); ListNode t = dummy; ListNode prev = head; for (int i = 0; p != null; i++, prev = p, p = p.next) { if (i % 2 != 0) { t.next = new ListNode(p.val); t = t.next; t.next = new ListNode(prev.val); t = t.next; } else if (p.next == null) { t.next = new ListNode(p.val); t = t.next; }
Anand Nageshwar Kumar
· 2 years ago
public ListNode swapPairs(ListNode head) { if(head == null || head.Next == null) return head; var temp = head.Next; head.Next = swapPairs(head.Next.Next); temp.Next = head; return temp; }
Reading Progress
0%