-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.java
88 lines (80 loc) · 1.62 KB
/
LinkedList.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
//-----------------------------------------------------
//Title: Stack
// Author: T. Emre Sen
//Description: This class defines LinkedList
//-----------------------------------------------------
package HW;
public class LinkedList {
protected Node head, tail;
protected int size = 0;
public LinkedList() {
head = tail = null;
size = 0;
}
//insert the node to the beginning of the list as a new head node if option is 0
//and to the end of the list if option is 1.
void insertToHeadOrTail(String newString, int option) {
Node newStr = new Node(newString);
if (option == 0) {
newStr.setNext(head);
head = newStr;
size++;
}
else if (option == 1) {
get(size).setNext(newStr);
size++;
}
}
//remove the node from the beginning of the list if option is 0
//and from the end of the list if option is 1.
public Node removeHeadOrTail(int option) {
if (size < 1) {
System.out.println("Error");
return null;
}
if (option == 0) {
Node n = head;
head = head.getNext();
n.setNext(null);
size--;
return n;
}
else if (option == 1) {
Node n = get(size);
get(size -1).setNext(null);
size--;
return n;
}
return null;
}
Node getFirst()
{
return head;
}
Node get(int i){
if(i > size){
System.out.println("Error.");
}
Node n = head;
for(int j = 1; j < i; j++)
n = n.getNext();
return n;
}
int getSize()
{
return size;
}
Node getNext(Node c)
{
return c.getNext();
}
@Override
public String toString() {
// TODO Auto-generated method stub
String s="";
for(int i = 1; i <= getSize(); i++){
s+=(get(i).getData() + " ");
}
return s;
}
}