-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedList.java
91 lines (80 loc) · 1.8 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
89
90
91
public class LinkedList {
// node class
static class Node{
int data;
Node next;
// constructor
Node(int data){
this.data = data;
}
}
// initialization
static Node head;
static int listItems;
static int listSize = 10;
// is empty
boolean isEmpty() { return (listItems==0); }
// is full
boolean isFull() { return (listItems==listSize); }
// append an item
void append(int data) {
// checking if list if full or not
if(isFull()) return;
// create new node
Node newNode = new Node(data);
// checking head and set new node the head if null
if(head==null) {
head = newNode;
return;
}
// set initial current node value
Node currentNode = head;
// finding the tail node
while(currentNode.next != null) {
currentNode = currentNode.next;
}
// set new node to the tail node next value
currentNode.next = newNode;
// node counter
listItems++;
}
// prepend item
void prepend(int data) {
if(isFull()) return;
// create new node
Node newNode = new Node(data);
// set head to the new node next value
newNode.next = head;
head = newNode;
// node counter
listItems++;
}
// remove list item
void remove(int data) {
// checking head data
if(head.data==data) {
head = head.next;
listItems--;
return;
}
// set initial node
Node current = head;
// finding the node to be deleted
while(current.next != null) {
if(current.next.data==data) {
current.next = current.next.next;
listItems--;
return;
}
current = current.next;
}
}
// traverse
void traverse() {
Node current = head;
while(current != null) {
System.out.println(current+" -- "+current.data+" -- "+current.next);
current = current.next;
}
}
}