-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.java
94 lines (67 loc) · 1.86 KB
/
LinkedList.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
91
92
93
94
package com.iamoperand.datastructures;
/**
* Created by iamoperand on 8/7/17.
*/
public class LinkedList {
Node head;
//made the class static to make the reference easier inside main function
static class Node{
int data;
Node next;
Node(int d){data = d;}
}
// This function prints contents of linked list starting from head
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
System.out.println();
}
//push a new node to the front
public void pushToFront(int data){
Node newNode = new Node(data);
if(head == null){
newNode.next = null;
}else{
newNode.next = head;
}
head = newNode;
printList();
}
//push a new node after some given node
public void pushAfter(Node prevNode, int data){
if(prevNode == null){
System.out.println("The node that you have provided doesn't exist");
return;
}
Node newNode = new Node(data);
newNode.next = prevNode.next;
prevNode.next = newNode;
}
//append the node at the end
public void append(int data){
Node newNode = new Node(data);
Node tempNode = head;
while(tempNode.next != null){
tempNode = tempNode.next;
}
tempNode.next = newNode;
newNode.next = null;
}
//initialising the linked-list
public static void main(String[] args){
LinkedList list = new LinkedList();
Node node = new Node(5);
node.next = null;
list.head = node;
list.printList();
list.pushAfter(node, 200);
list.printList();
list.append(69);
list.printList();
}
}