-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkerListDemo.java
159 lines (133 loc) · 2.52 KB
/
LinkerListDemo.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//-----------------------------------------Linked List Implementation-------------by_Abd----//
class LinkedList
{
Node head;
//creating Node Structure//
class Node
{
int data;
Node next;
Node(int val)
{
data = val;
next = null;
}
}
LinkedList(){
head =null;
}
// insert node beginning of the List //
public void insertAtBeg(int val)
{
Node newNode=new Node(val);
if(head == null)
{
head = newNode;
System.out.println("Entered value is :"+ newNode.data);
}
else {
newNode.next =head;
head=newNode;
System.out.println("Entered value is :"+ newNode.data);
}
}
// Traverse (Display) the List //
public void display() {
System.out.println();
Node temp=head;
while(temp != null)
{
System.out.print( temp.data+" ");
temp=temp.next;
//System.out.print(temp.data);
}
}
// insert the node at specific position //
public void insertAtPos(int pos, int val)
{
Node newNode=new Node(val);
Node temp=head;
if(pos == 0)
{
insertAtBeg(val);
return;
}
for(int i=1; i<pos; i++)
{
temp=temp.next;
if(temp == null)
{
System.err.println("Invalid position ");
return;
}
}
newNode.next=temp.next;
temp.next=newNode;
}
// deleting node at specific position //
public void deleteAtPos(int pos)
{
Node temp=head;
Node pre = null;
if(pos == 0)
{
deleteAtBeg(0);
return;
}
for (int i=1; i<pos; i++)
{
pre=temp;
temp=temp.next;
}
pre.next=temp.next;
}
// deleting Last Node //
public void deleteAtLast() {
Node temp =head;
while(temp.next.next!=null)
{
temp=temp.next;
}
temp.next=null;
}
// Reversing LinkedList //
public void reverse()
{
Node prev=null;
Node cur=head;
Node next=head.next;
while(cur != null)
{
next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
head=prev;
}
// deleting Node at Beginning of the List //
public void deleteAtBeg(int pos)
{
if(head==null)
{
System.out.println("List is Empty");
return;
}
head=head.next;
}
}
public class LinkerListDemo {
public static void main(String[] args) {
LinkedList list =new LinkedList();
list.insertAtBeg(8);
list.insertAtBeg(9);
list.insertAtBeg(10);
list.insertAtBeg(11);
list.insertAtBeg(12);
list.display();
list.reverse();
list.display();
list.deleteAtLast();
list.display();
}
}