-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListNode.java
90 lines (72 loc) · 2.02 KB
/
LinkedListNode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.Scanner;
class LinkedList {
Node head;
class Node {
int data;
Node next;
Node(int n) {
data = n;
next = null;
}
}
public void push(int d) {
Node newNode = new Node(d);
if (head == null) {
head = newNode;
} else {
Node curNode = head;
while (curNode.next != null) {
curNode = curNode.next;
}
curNode.next = newNode;
}
}
public void print() {
if (head == null) {
System.out.println("No node to show");
} else {
Node curNode = head;
while (curNode.next != null) {
System.out.print(curNode.data + " -> ");
curNode = curNode.next;
}
System.out.println(curNode.data);
}
}
public Node find(int d) {
System.out.println("Looking for " + d);
Node curNode = head;
while (curNode.next != null) {
if (curNode.data == d) return curNode;
curNode = curNode.next;
}
if (curNode.data == d) return curNode;
System.out.println("Number " + d + " not found");
return null;
}
public void insertAfter(int target, int newNumber) {
Node newNode = new Node(newNumber);
boolean isInserted = false;
Node targetNode = find(target);
if (targetNode != null) {
Node nextNode = targetNode.next;
targetNode.next = newNode;
newNode.next = nextNode;
}
}
}
public class LinkedListNode {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList listl = new LinkedList();
for (int i = 0; i < 5; i ++) {
int n = sc.nextInt();
listl.push(n);
}
listl.print();
int new1 = sc.nextInt();
listl.insertAfter(new1, 999);
listl.insertAfter(15, 33);
listl.print();
}
}