-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSinglyLinkedList.java
74 lines (68 loc) · 1.34 KB
/
SinglyLinkedList.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
public class SinglyLinkedList<E> {
//--------nested node class------
private static class Node<E>{
private E element; //reference to the element stored at this node
private Node<E> next; //reference to the subsequent node in the kist
public Node(E e,Node<E> n){
element = e;
next = n;
}
public E getElement(){
return element;
}
public Node<E> getNext(){
return next;
}
public void setNext(Node<E> n){
next = n;
}
}
//---------end of the nested class-----
//instance variables of the SinglyLinledList
private Node<E> head = null;
private Node<E> tail = null;
private int size = 0;
public SinglyLinkedList(){}
//access methods
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public E first(){
if(isEmpty())
return null;
return head.getElement();
}
public E last(){
if(isEmpty()) return null;
return tail.getElement();
}
public void addFirst(E e){
head = new Node<>(e,head);
if(size == 0 )
tail = head;
size++;
}
public void addLast(E e){
Node<E> newest = new Node<>(e,null);
if(isEmpty()){
head = newest;
}
else
tail.setNext(newest);
tail=newest;
size++;
}
public E removeFirst(){
if(isEmpty()) return null;
E answer = head.getElement();
head = head.getNext();
size--;
if(size == 0){
tail = null;
}
return answer;
}
}