-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortedLinkedList.java
63 lines (55 loc) · 1.22 KB
/
SortedLinkedList.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
//-----------------------------------------------------
//Title: Stack
// Author: T. Emre Sen
//Description: This class defines SortedLinkedList
//-----------------------------------------------------
package HW;
public class SortedLinkedList {
protected Node head;
private int size;
public SortedLinkedList()
{
Node n = new Node(null);
}
//insert the node to the beginning of the list if list is empty.
void insert (String newStr)
{
Node a = new Node(newStr);
Node n = head;
if (head == null) {
n.setNext(head);
head = n;
size++;
return;
}
//insert the node to the beginning of the list as a new node in terms of
//alphabetical order
while (n.getNext() != null && a.compareTo(n.getNext()) < 0)
{
n=n.getNext();
}
n.setNext(a.getNext());
a.setNext(n);
size++;
}
public boolean remove (String remStr) {
//checks if the list is empty or not
Node b = new Node(remStr);
Node n = head;
if (n == null) {
return false;
}
while (n.getNext() != null)
{
n = n.getNext();
//checks if there is any duplicate node with the same data
if (b.getData().equals(n.getData()))
{
n.setNext(n.getNext().getNext());
size--;
return true;
}
}
return false;
}
}