MCPcopy Create free account
hub / github.com/careercup/ctci / partition

Method partition

java/Chapter 2/Question2_4/Question.java:7–44  ·  view source on GitHub ↗
(LinkedListNode node, int x)

Source from the content-addressed store, hash-verified

5public class Question {
6
7 public static LinkedListNode partition(LinkedListNode node, int x) {
8 LinkedListNode beforeStart = null;
9 LinkedListNode beforeEnd = null;
10 LinkedListNode afterStart = null;
11 LinkedListNode afterEnd = null;
12
13 /* Partition list */
14 while (node != null) {
15 LinkedListNode next = node.next;
16 node.next = null;
17 if (node.data < x) {
18 if (beforeStart == null) {
19 beforeStart = node;
20 beforeEnd = beforeStart;
21 } else {
22 beforeEnd.next = node;
23 beforeEnd = node;
24 }
25 } else {
26 if (afterStart == null) {
27 afterStart = node;
28 afterEnd = afterStart;
29 } else {
30 afterEnd.next = node;
31 afterEnd = node;
32 }
33 }
34 node = next;
35 }
36
37 /* Merge before list and after list */
38 if (beforeStart == null) {
39 return afterStart;
40 }
41
42 beforeEnd.next = afterStart;
43 return beforeStart;
44 }
45
46 public static void main(String[] args) {
47 /* Create linked list */

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected