-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenDoubleLinkedList.java
131 lines (126 loc) · 2.83 KB
/
GenDoubleLinkedList.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
/*
* Written by Noah Shaw
*/
public class GenDoubleLinkedList <T> {
//Internal class
private class ListNode
{
private T data;
private ListNode nextLink;
private ListNode prevLink;
public ListNode()
{
data = null;
nextLink = null;
prevLink = null;
}
public ListNode(T aData, ListNode aNextLink, ListNode aPrevLink)
{
data = aData;
nextLink = aNextLink;
prevLink = aPrevLink;
}
}
//Instance variables
private ListNode head; //Point to the first item in the list
private ListNode curr; //Current node of interest
//Constructor
public GenDoubleLinkedList()
{
head = curr = null;
}
//Methods
public void goToNext() //Goes to the next node in the list
{
if(curr == null || curr.nextLink == null)
{
return;
}
curr = curr.nextLink;
}
public void goToPrev() //Goes to the previous node
{
if(curr == null || curr.prevLink == null)
{
return;
}
curr = curr.prevLink;
}
public T getDataAtCurrent() //Returns the data at the current node
{
if(curr != null)
{
return curr.data;
}
return null;
}
public void setDataAtCurrent(T aData) //Sets the data at the current node
{
if(curr != null)
{
curr.data = aData;
}
}
public void insert(T aData) //Inserts a new node at the end of the list
{
ListNode newNode = new ListNode(aData, null, null);
if(head == null) //List is empty
{
head = newNode;
curr = head;
return;
}
ListNode temp = head; //List is not empty
while(temp.nextLink != null)
{
temp = temp.nextLink;
}
temp.nextLink = newNode;
}
public void insertNodeAfterCurrent(T aData) //Inserts a new node after the current node
{
if(curr == null)
{
return;
}
ListNode newNode = new ListNode(aData, curr.nextLink, curr);
curr.nextLink = newNode;
}
public void deleteCurrentNode() //Deletes the current node
{
if(curr != null && curr.prevLink != null) //Current is in the middle of the list
{
curr.prevLink.nextLink = curr.nextLink;
curr.nextLink.prevLink = curr.prevLink;
curr = curr.nextLink;
}
else if(curr != null) //Current is at the head
{
head = head.nextLink;
}
}
public void showList() //Prints the list
{
for(ListNode temp = head; temp != null; temp = temp.nextLink)
{
System.out.println(temp.data);
}
}
public boolean inList(T aData) //Determines if a data is in the list
{
return this.findNodeWith(aData) != null;
}
private ListNode findNodeWith(T aData) //Finds the node with a data
{
ListNode temp = head;
while(temp != null)
{
if(temp.data.equals(aData))
{
return temp;
}
temp = temp.nextLink;
}
return null;
}
}