-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.java
110 lines (91 loc) · 2.41 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* Created by newuser on 11/21/15.
*/
public class LinkedList {
node head;
public LinkedList(){
head=null;
}
public boolean empty(){
return (head==null);
}
public void display(){
node current = head;
while(current!=null){
System.out.println(current.data);
current=current.next;
}
}
public void insert(double data){
node newnode = new node(data);
if (empty()){
head = new node(data);
}else{
node current = head;
while (current.next!=null){
current=current.next;
}
current.next = newnode;
}
}
public double search(double data){
if (empty()){
return Double.POSITIVE_INFINITY;
}else{
for(node current =head; current!=null; current=current.next){
if (current.data==data){
return current.data;
}
}
}
return Double.POSITIVE_INFINITY;
}
public node reverse(node list){
//empty or one element list is already reversed
//1.)Base case (3|null) or (null)
if (list==null||list.next==null){
return list;
}
//List = (3| next ) -> (4|null)
node second = list.next;
//unlink the list
//List = (3|null)
list.next = null;
//(4|null)
node reversedList = reverse(second);
//create link with original list
//reversedList = (4|next) -> (3|null)
second.next = list;
return reversedList;
}
public void delete(double data){
if (empty()){
System.out.println("EMPTY");
return;
}else if(head.data==data){
if(!empty()) {
head = head.next;
}else {
head=null;
}
}else{
node current = head;
node previous =head;
while (current.next!=null){
if (current.data==data){
previous.next = current.next;
}
previous = current;
current=current.next;
}
}
}
class node {
double data;
node next;
public node(double data){
this.data = data;
next = null;
}
}
}