-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyGenericDS.java
More file actions
97 lines (83 loc) · 1.89 KB
/
MyGenericDS.java
File metadata and controls
97 lines (83 loc) · 1.89 KB
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
package oc;
public class MyGenericDS<E> implements OrderedCollection<E> {
public Node<E> end;// the last Node stored
private int length = 0;
class Node<E> {
private int position;
E element;// setting the object for the current node
Node<E> next;// initializing the next node
public Node(E elem) {
element = elem;
position = length;
length+=1;
}
}
public E peek() {
return end.element;
}
@Override
public E pop() {
E toReturn = end.element;// creating local variable for end.num
end = end.next;// changing 'index' to the previous node
return toReturn;
}
public MyGenericDS() {
end = null;// setting value to null
}
public void add(E Add) {
Node<E> toAdd = new Node<E>(Add);
toAdd.element = Add;
toAdd.next = end;// making this known as the last node
end = toAdd;
}
public void append(E toAppend) {
Node<E> toAdd = new Node<E>(toAppend);
toAdd.element = toAppend;
toAdd.next = end;// making this known as the last node
end = toAdd;
}
public String toString() {
String toReturn = "";
Node<E> n = end;
while (n != null) {
toReturn = n.element.toString() + " " + toReturn;
n = n.next;
}
return toReturn;
}
public int length() {
int num = 0;
Node<E> n = end;
while (n != null) {
num++;
n = n.next;
}
return num;
}
@Override
public void remove(int index) {
// TODO Auto-generated method stub
Node<E> toCheck = end;
try {
if (index > length || index < 0) {
throw new Exception();
}
} catch (Exception e) {
System.out.println("Please use a valid index");
}
try {
while(toCheck !=null) {
if (index == length-1 && toCheck.position == length-1) {
pop();
}
else if (toCheck.position == index + 1) {
toCheck.next = toCheck.next.next;
}
toCheck = toCheck.next;
}
}
catch(Exception e1) {
System.out.println("something went wrong in the process of removing");
}
}
}