-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSignlyLinkedList.java
107 lines (105 loc) · 2.77 KB
/
SignlyLinkedList.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
class SignlyLL<E>{
private Node<E> head = null;
private Node<E> tail = null;
private int size = 0;
public void SignlyLinkedList(){}
// access methods
public int size(){return size;}
public boolean isEmpty() {return size==0;}
private static class Node<E> {
private E element;
private Node<E> next;
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;
}
}
public void display() {
Node<E> temp = head;
while (temp != null) {
System.out.print(temp.element + " ");
temp = temp.next;
}
System.out.println();
}
public E first(){
if (isEmpty()) {
return null;
}
return head.getElement();
}
public E last(){
if (isEmpty()) {
return null;
}
return tail.getElement();
}
//upadate methods
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;
}
}
public class SignlyLinkedList{
public static void main(String[] args){
// SignlyLL<Integer> sll = new SignlyLL<>();
// sll.addFirst(5);
// sll.addFirst(6);
// sll.addFirst(7);
// sll.addFirst(8);
// sll.addFirst(9);
// sll.addFirst(10);
// sll.addFirst(4);
// System.out.println("Head"+sll.first());
// System.out.println("Tail: "+sll.last());
// System.out.println("Total Element: "+sll.size());
// System.out.println("All element in this SLL list");
// sll.display();
SignlyLL<String> sll = new SignlyLL<>();
sll.addFirst("Hello");
sll.addFirst("Rajendra");
sll.addFirst("Pancholi");
sll.addFirst("!");
sll.addLast("last element.");
System.out.println("Head Element: "+sll.first());
System.out.println("Tail Element: "+sll.last());
System.out.println("Total Element: "+sll.size());
System.out.println("All element in this SLL list");
sll.display();
}
}