Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Alternative iterative way in Java

Davide Pugliese

Jul 18, 2024

// 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; } } return dummy.next; } }

0

0

Comments
Comments
J
Jimmy a year ago

Your code works but you're creating new ListNodes instead of swapping the existing ones. You will use O(N) extra space.

On this page