Skip to content

Commit 076d848

Browse files
committed
Refactored Swap Nodes in Pairs.java
1 parent 5f511d1 commit 076d848

File tree

2 files changed

+30
-29
lines changed

2 files changed

+30
-29
lines changed

Medium/Swap Nodes in Pair.java

Lines changed: 0 additions & 29 deletions
This file was deleted.

Medium/Swap Nodes in Pairs.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode() {}
7+
* ListNode(int val) { this.val = val; }
8+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
public ListNode swapPairs(ListNode head) {
13+
ListNode curr = head;
14+
ListNode prev = null;
15+
while (curr != null && curr.next != null) {
16+
ListNode nextNode = curr.next;
17+
if (curr == head) {
18+
head = nextNode;
19+
}
20+
curr.next = nextNode.next;
21+
nextNode.next = curr;
22+
if (prev != null) {
23+
prev.next = nextNode;
24+
}
25+
prev = curr;
26+
curr = curr.next;
27+
}
28+
return head;
29+
}
30+
}

0 commit comments

Comments
 (0)