-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d1360fc
commit 0ca45c5
Showing
2 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
src/main/java/cracking/the/code/interview/chapter4/DoublyLinkedList.java
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,41 @@ | ||
package cracking.the.code.interview.chapter4; | ||
|
||
public class DoublyLinkedList { | ||
|
||
|
||
public static void main (String... args) { | ||
|
||
Node n = new Node(); | ||
insert(n,1); | ||
insert(n,2); | ||
insert(n,3); | ||
insert(n,4); | ||
insert(n,5); | ||
|
||
} | ||
|
||
private static class Node { | ||
Node next; | ||
Node previous; | ||
Integer value; | ||
} | ||
|
||
private static Node insert(Node node, int v) { | ||
|
||
if (node.value == null) { | ||
node.value = v; | ||
return node; | ||
} | ||
|
||
if (node.next == null) { | ||
node.next = new Node(); | ||
node.next.previous = node; | ||
} | ||
|
||
node.next = insert(node.next, v); | ||
|
||
return node; | ||
} | ||
|
||
|
||
} |
40 changes: 40 additions & 0 deletions
40
src/main/java/cracking/the/code/interview/chapter4/SinglyLinkedList.java
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,40 @@ | ||
package cracking.the.code.interview.chapter4; | ||
|
||
public class SinglyLinkedList { | ||
|
||
|
||
public static void main(String... args) { | ||
|
||
Node root = new Node(); | ||
|
||
insert(root, 1); | ||
insert(root, 2); | ||
insert(root, 3); | ||
insert(root, 4); | ||
insert(root, 5); | ||
|
||
|
||
} | ||
|
||
private static class Node { | ||
private Node next; | ||
private Integer value; | ||
} | ||
|
||
private static Node insert(Node node, int v) { | ||
var child = node; | ||
if(child.value == null) { | ||
child.value = v; | ||
return child; | ||
} | ||
|
||
if(child.next == null) { | ||
child.next = new Node(); | ||
} | ||
|
||
child.next = insert(child.next, v); | ||
|
||
return node; | ||
} | ||
|
||
} |