-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathRemoveNthNodeFromList.java
172 lines (141 loc) · 3.15 KB
/
RemoveNthNodeFromList.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
160
161
162
163
164
165
166
167
168
169
170
171
172
import java.util.*;
class node
{
int Data;
node next;
};
class RemoveNthNodeFromList{
private int size;
private node Head;
/**
* Initialize an size and head of the SinglyLinkedList
*/
RemoveNthNodeFromList()
{
this.size = 0;
this.Head = null;
}
/**
* Function to display all elements of the SinglyLinkedList
*/
public void Display()
{
node temp = Head;
while(temp != null)
{
System.out.print("|"+temp.Data+"|->");
temp = temp.next;
}
System.out.print(" NULL\n");
}
/**
* Function to insert elements into SinglyLinkedList
*/
public void Insert(int no)
{
node newn = new node();
newn.Data = no;
newn.next = null;
if(Head == null)
{
Head = newn;
}
else
{
node temp = Head;
while(temp.next != null)
{
temp = temp.next;
}
temp.next = newn;
}
size++;
}
/**
* Function to delete first element from SinglyLinkedList
*/
public void DeleteFirst()
{
if(Head == null)
{
return;
}
else
{
Head = Head.next;
System.gc();
}
size--;
}
/**
* Function to delete last element from SinglyLinkedList
*/
public void DeleteLast()
{
node temp = Head;
if(Head == null)
{
return;
}
else
{
while(temp.next.next != null)
{
temp = temp.next;
}
temp.next = null;
System.gc();
}
size--;
}
/**
* Function to delete element from any position in SinglyLinkedList
*/
public void DeleteAtPos(int ipos)
{
node Target = null;
int i = 0;
if((ipos < 1) || (ipos > size))
{
System.out.println("Invalid Position");
return;
}
else if(ipos == 1)
{
DeleteFirst();
}
else if(ipos == size)
{
DeleteLast();
}
else
{
node temp = Head;
for(i = 1; i <= ipos - 1; i++)
{
temp = temp.next;
}
Target = temp.next.next;
temp.next = Target;
System.gc();
size--;
}
}
public static void main(String args[]) {
int iRet = 0;
int iValue = 1;
int iChoice = 0;
int ipos = 0;
Scanner sc = new Scanner(System.in);
RemoveNthNodeFromList sobj = new RemoveNthNodeFromList();
sobj.Insert(1);
sobj.Insert(2);
sobj.Insert(3);
sobj.Insert(4);
sobj.Insert(5);
sobj.Display();
sobj.DeleteAtPos(1);
sobj.Display();
sc.close();
}
}