-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
120 lines (119 loc) · 2.61 KB
/
LinkedList.java
File metadata and controls
120 lines (119 loc) · 2.61 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author James
*/
public class LinkedList
{
Node head;
int size;
public class Node //Node Class
{
int data;
Node next;
public Node (int myData)
{
data = myData;
next = null;
}
}
public LinkedList() //Linked List starts at 0
{
size = 0;
head = null;
}
public boolean isEmpty () //Check if empty
{
if (size == 0)
{
return true;
}
return false;
}
public Node find(int theData) // find the data in the nodes
{
Node temp = head;
if(isEmpty())
{
return null;
}
else
{
while (temp != null)
{
if(theData != temp.data)
{
temp = temp.next;
}
else
{
return temp;
}
}
return null;
}
}
public Node findPrev(int theData) // find prev node
{
Node temp = head;
if(isEmpty())
{
return null;
}
else
{
if(temp.data == theData)
{
return temp;
}
while (temp.next != null)
{
if(theData != temp.next.data)
{
temp = temp.next;
}
else
{
return temp;
}
}
return null;
}
}
public void insert(int newData) //insert the data at the given index every time
{
Node newNode = new Node(newData);
newNode.next = head;
head = newNode;
size++;
}
public void remove(int theData) // remove node based on data
{
Node foundNodePrev = findPrev(theData);
if(!isEmpty() && foundNodePrev != null)
{
if(head.data == theData)
{
head = head.next;
}
else
{
foundNodePrev.next = foundNodePrev.next.next;
}
size--;
}
}
public void print()
{
Node n = head;
while(n != null)
{
System.out.print(n.data+ " ");
n = n.next;
}
}
}