Grokking Data Structures & Algorithms for Coding Interviews
Vote

0% completed

​

Solution: Swap Nodes in Pairs

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 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; } }
A

Anonymous

· 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; }
Show 1 reply
A

Anonymous

· 3 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%


Vote for new content