-
-
Save InterviewBytes/1f478196d5fabc1beb7bcfe74eda5b5a to your computer and use it in GitHub Desktop.
Swap Pairs in Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class SwapPairs { | |
public ListNode swapPairs(ListNode head) { | |
if (head == null || head.next == null) return head; | |
ListNode next = head.next.next; | |
ListNode temp = head; | |
head = head.next; | |
head.next = temp; | |
head.next.next = swapPairs(next); | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment