FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
java-basics/java-programs/LinkedListCheckCyclic.java at master · CodeForHunger/java-basics · GitHub
CodeForHunger
/
java-basics
Public
forked from
learning-zone/java-basics
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
java-basics
/
java-programs
/
LinkedListCheckCyclic.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
57 lines (50 loc) · 1.49 KB
Breadcrumbs
java-basics
/
java-programs
/
LinkedListCheckCyclic.java
Copy path
File metadata and controls
57 lines (50 loc) · 1.49 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
misc
;
import
java
.
util
.
HashSet
;
/**
* Algorithm:-
* 1) Use two pointers fast and slow
* 2) Move fast two nodes and slow one node in each iteration
* 3) If fast and slow meet then linked list contains cycle
* 4) If fast points to null or fast.next points to null then linked list is not cyclic
*
*/
public
class
LinkedListCheckCyclic
{
static
Node
head
;
// head of list
/* Linked list Node*/
static
class
Node
{
int
data
;
Node
next
;
Node
(
int
d
) {
data
=
d
;
next
=
null
; }
}
/* Inserts a new Node at front of the list. */
static
public
void
push
(
int
new_data
) {
Node
new_node
=
new
Node
(
new_data
);
new_node
.
next
=
head
;
head
=
new_node
;
}
static
boolean
isCyclic
() {
Node
fast
=
head
;
Node
slow
=
head
;
while
(
fast
!=
null
&&
fast
.
next
!=
null
) {
fast
=
fast
.
next
.
next
;
slow
=
slow
.
next
;
if
(
fast
==
slow
) {
return
true
;
}
}
return
false
;
}
public
static
void
main
(
String
[]
args
) {
LinkedListCheckCyclic
linkedList
=
new
LinkedListCheckCyclic
();
linkedList
.
push
(
101
);
linkedList
.
push
(
201
);
linkedList
.
push
(
301
);
linkedList
.
push
(
401
);
/*Create loop for testing */
// linkedList.head.next.next.next.next = linkedList.head;
if
(
isCyclic
())
System
.
out
.
println
(
"Linked List is Cyclic !!!"
);
else
System
.
out
.
println
(
"Linked List is Not Cyclic !"
);
}
}
Back
|
FazBrowse Home
|
New Git URL