-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathLinear List
167 lines (165 loc) · 3.64 KB
/
Linear List
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
class LinearList<D> implements List<D>
{
ListObject<D> head,tail;
LinearList()
{
head=null;
tail=null;
}
public void add(D v)
{
if(head==null)
{
ListObject<D> ob=new ListObject<D>(v);
head=ob;
tail=ob;
}
else
{
ListObject<D> ob=new ListObject<D>(v);
tail.next=ob;
tail=ob;
}
}
public void add(D v,Integer pos)
{
Integer size=getSize();
Integer p=1;
//ListObject k=null;
try
{
if(pos>(size+1))
{
BoundsException ob=new BoundsException();
throw ob;
}
}
catch(BoundsException x)
{
x.printError();
return;
}
if(pos==1)
{
ListObject<D> ob=new ListObject<D>(v);
ob.next=head;
head=ob;
}
if(pos>1 && pos<=size)
{
ListObject<D> ob=new ListObject<D>(v);
for(ListObject<D> i=head;i!=null;i=i.next)
{
++p;
if(p==pos)
{
ob.next=i.next;
i.next=ob;
break;
}
}
}
if(pos==(size+1))
{
ListObject<D> ob=new ListObject<D>(v);
tail.next=ob;
tail=ob;
}
}
public boolean remove(D m)
{
Integer p=0;
Integer size=getSize();
for(ListObject<D> i=head;i!=null;i=i.next)
{
++p;
if(i.val==m)
{
if(p==1)
head=head.next;
else
{
Integer p1=1;
for(ListObject<D> j=head;j!=null;j=j.next)
{
++p1;
if(p1==p)
{
j.next=j.next.next;
break;
}
}
}
return true;
}
}
return false;
}
public Integer search(D v)
{
Integer p=-1;
for(ListObject<D> i=head;i!=null;i=i.next)
{
++p;
if(i.val==v)
return (p);
}
return -1;
}
public D getElementAt(Integer pos)
{
Integer p=0;
Integer size=getSize();
try
{
if(pos>(size+1))
{
BoundsException ob=new BoundsException();
throw ob;
}
}
catch(BoundsException x)
{
x.printError();
return null;
}
for(ListObject<D> i=head;i!=null;i=i.next)
{
++p;
if(p==pos)
return i.val;
}
return null;
}
public void reverse()
{
Integer size=getSize();
int p=size;
Object ob[]=new Object[size];
for(ListObject<D> i=head;i!=null;i=i.next)
ob[--p]=i.val;
for(ListObject<D> i=head;i!=null;i=i.next)
i.val=(D)ob[p++];
}
public Integer getSize()
{
Integer j=0;
for(ListObject<D> i=head;i!=null;i=i.next)
++j;
return j;
}
public boolean isEmpty()
{
Integer size=getSize();
if(size==0)
return true;
return false;
}
public void traverse()
{
for(ListObject<D> i=head;i!=null;i=i.next)
{
System.out.print(i.val+" ");
}
}
}