-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlscopy.java
More file actions
143 lines (130 loc) · 2.14 KB
/
Copy pathlscopy.java
File metadata and controls
143 lines (130 loc) · 2.14 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package linkedl;
import linkedl.linkedlistll;
import linkedl.node;
//import linkedlist.Node;
class node{
int val;
node next;
node(int data)
{
this.val=data;
this.next=null;
}
}
class linkedlistll{
node head;
linkedlistll()
{
this.head=null;
}
//TO_PRINT_A_LINKED_LIST
void print(){
node cur = this.head;
while(cur!=null){
System.out.print(cur.val+" ");
cur = cur.next;
}
System.out.println();
}
//LENGTH_OF_LINKEDLIST
int length(){
node cur = this.head;
int c=0;
while(cur!=null){
c++;
cur = cur.next;
}
return c;
}
//SEARCHING_A_KEY_VALUE
boolean search(int key)
{
node cur=this.head;
while(cur!=null)
{
if(cur.val==key)
{
return true;
}
cur=cur.next;
}
return false;
}
// node middle()
// {
// node cur=this.head;
// int len=this.length();
// int mid=len/2;
// int p=0;
// while(p!=mid)
// {
// cur=cur.next;
// p++;
// }
// return cur;
// }
node middle()
{
node slow=this.head;
node fast=this.head;
while(slow!=null && fast!=null && fast.next!=null)
{
slow=slow.next;
fast=fast.next.next;
}
return slow;
}
//INSERTIONATEND
void insertatend(int data)
{
node cur=this.head;
node newnode = new node(data);
if(cur==null)
{
this.head=newnode;
}
else
{
while(cur.next!=null)
{
cur=cur.next;
}
cur.next=newnode;
}
}
//DELETIONATEND
void deleteatend()
{
node cur=this.head;
if(cur==null||cur.next==null)
{
this.head=null;
}
else
{
while(cur.next.next!=null)
{
cur=cur.next;
}
cur.next=null;
}
}
}
public class lscopy {
public static void main(String[] args) {
// TODO Auto-generated method stub
linkedlistll ls=new linkedlistll();
int []nodes= {1,2,3,4,5,6,7,8,9};
for(int val:nodes)
{
ls.insertatend(val);
}
ls.print();
ls.deleteatend();
ls.print();
ls.length();
System.out.println(ls.search(5));
node mid = ls.middle();
System.out.println(mid.val);
}
}