Skip to content

Commit 0852186

Browse files
Nickx58t2013anurag
authored andcommitted
Create Linkedlist-insertion (hacktoberfest17#931)
1 parent 7cf096f commit 0852186

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package linkedlist;
2+
3+
class LinkedList {
4+
Node head;
5+
6+
static class Node {
7+
int data;
8+
Node next;
9+
10+
Node(int data) {
11+
this.data = data;
12+
next = null;
13+
}
14+
}
15+
16+
public void printList() {
17+
Node n = head;
18+
while(n!=null) {
19+
System.out.print(n.data+" ");
20+
n = n.next;
21+
}
22+
}
23+
24+
public void push(int data) {
25+
Node new_node = new Node(data);
26+
new_node.next = head;
27+
head = new_node;
28+
}
29+
30+
public void insertAfter(Node prev_node, int data) {
31+
if(prev_node == null) {
32+
System.out.print("Prev Node cannot be null");
33+
return;
34+
}
35+
36+
Node new_node = new Node(data);
37+
new_node.next = prev_node.next;
38+
prev_node.next = new_node;
39+
}
40+
41+
public void append(int data) {
42+
Node new_node = new Node(data);
43+
if(head == null) {
44+
head = new Node(data);
45+
return;
46+
}
47+
new_node.next = null;
48+
Node last = head;
49+
while(last.next != null){
50+
last = last.next;
51+
}
52+
53+
last.next = new_node;
54+
return;
55+
56+
57+
}
58+
public static void main(String args[]) {
59+
LinkedList ll = new LinkedList();
60+
ll.push(8);
61+
ll.append(7);
62+
ll.append(5);
63+
ll.printList();
64+
65+
}
66+
}

0 commit comments

Comments
 (0)