File tree Expand file tree Collapse file tree 2 files changed +62
-0
lines changed
Expand file tree Collapse file tree 2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ Given a linked list and a value * x* , partition it such that all nodes less than * x* come before nodes greater than or equal to * x* .
2+
3+ You should preserve the original relative order of the nodes in each of the two partitions.
4+
5+ For example,
6+ Given ` 1->4->3->2->5->2 ` and * x* = 3,
7+ return ` 1->2->2->4->3->5 ` .
Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * public class ListNode {
4+ * int val;
5+ * ListNode next;
6+ * ListNode(int x) { val = x; }
7+ * }
8+ */
9+ public class Solution {
10+ public ListNode partition (ListNode head , int x ) {
11+ if (head == null ) {
12+ return null ;
13+ }
14+
15+ ListNode ltHead = null ;
16+ ListNode ltNode = null ;
17+ ListNode geHead = null ;
18+ ListNode geNode = null ;
19+ ListNode currNode = head ;
20+
21+ while (currNode != null ) {
22+ if (currNode .val < x ) {
23+ if (ltHead == null ) {
24+ ltHead = currNode ;
25+ ltNode = currNode ;
26+ } else {
27+ ltNode .next = currNode ;
28+ ltNode = ltNode .next ;
29+ }
30+ } else {
31+ if (geHead == null ) {
32+ geHead = currNode ;
33+ geNode = currNode ;
34+ } else {
35+ geNode .next = currNode ;
36+ geNode = geNode .next ;
37+ }
38+ }
39+
40+ currNode = currNode .next ;
41+ }
42+
43+ if (geNode != null ) {
44+ geNode .next = null ;
45+ }
46+
47+ if (ltNode != null ) {
48+ ltNode .next = geHead ;
49+ } else {
50+ ltHead = geHead ;
51+ }
52+
53+ return ltHead ;
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments