Skip to content

Commit

Permalink
Swap Nodes in Pairs: Accepted
Browse files Browse the repository at this point in the history
  • Loading branch information
gouthampradhan committed Aug 13, 2017
1 parent 51b4970 commit fa90d78
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ My accepted leetcode solutions to some of the common interview problems.
- [Reverse Linked List](problems/src/linked_list/ReverseLinkedList.java) (Easy)
- [Delete Node in a Linked List](problems/src/linked_list/DeleteNode.java) (Easy)
- [Reverse Nodes in k-Group](problems/src/linked_list/ReverseNodesKGroup.java) (Hard)
- [Swap Nodes in Pairs](problems/src/linked_list/SwapNodesInPairs.java) (Medium)

#### [Math](problems/src/math)

Expand Down
58 changes: 58 additions & 0 deletions problems/src/linked_list/SwapNodesInPairs.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package linked_list;

/**
* Created by gouthamvidyapradhan on 13/08/2017.
* Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
*/
public class SwapNodesInPairs {

public static class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
}

public static void main(String[] args) throws Exception{
ListNode node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);
node.next.next.next = new ListNode(4);
node.next.next.next.next = new ListNode(5);
node.next.next.next.next.next = new ListNode(6);
ListNode head = new SwapNodesInPairs().swapPairs(node);
while(head != null){
System.out.println(head.val);
head = head.next;
}
}

public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode newHead = head.next;
ListNode curr = head.next;
ListNode prev = head;
ListNode prevPrev = new ListNode(-1); //dummy node
while(curr != null){
prev.next = curr.next;
curr.next = prev;
prevPrev.next = curr;
if(prev.next != null){
curr = prev.next.next;
prev = prev.next;
prevPrev = prevPrev.next.next;
} else {
curr = null;
}
}
return newHead;
}

}

0 comments on commit fa90d78

Please sign in to comment.