-
Notifications
You must be signed in to change notification settings - Fork 118
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #356 from Xuewei-Chen/main
PartitionList
- Loading branch information
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
//This algorithm is to partition it such that all nodes less than x come before nodes greater than or equal to x. | ||
|
||
import java.io.*; | ||
|
||
class Solution{ | ||
public ListNode partition(ListNode head, int x){ | ||
ListNode small = new ListNode(0); | ||
ListNode large = new ListNode(0); | ||
|
||
ListNode p1 = small; | ||
ListNode p2 = large; | ||
|
||
while(head != null){ | ||
if(head.val < x){ | ||
p1.next = head; | ||
p1 = p1.next; | ||
}else{ | ||
p2.next = head; | ||
p2 = p2.next; | ||
} | ||
head = head.next; | ||
} | ||
p2.next = null; | ||
p1.next = large.next; | ||
return small.next; | ||
} | ||
} | ||
|