-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListLoop.java
More file actions
86 lines (78 loc) · 2.27 KB
/
LinkedListLoop.java
File metadata and controls
86 lines (78 loc) · 2.27 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
package Codes;
import java.util.Scanner;
public class LinkedListLoop {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
static void append(int d) {
Node newnode = new Node(d);
if (head == null) {
head = newnode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newnode;
}
}
static boolean detectloop() {
Node slow = head, fast = head;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
System.out.println("loop present");
return true;
}
else System.out.println("loop not present");
}
return false;
}
static void createaloop(Node temp, int node) {
int i = 0;
Node last = temp;
Node value = temp;
while (last.next != null) {
last = last.next;
}
while (value.next != null && i < node) {
value = value.next;
}
if (value==temp)
last.next = null;
else last.next=value;
}
static void display() {
Node print = head;
while (print.next != null) {
System.out.print(print.data + " ");
print = print.next;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedListLoop obj = new LinkedListLoop();
// System.out.println("enter number of testcases");
// int t = sc.nextInt();
int element = 0;
int node = 0;
// for (int j = 0; j < t; j++) {
System.out.println("enter length");
int length = sc.nextInt();
System.out.println("enter elements");
for (int i = 0; i < length; i++) {
append(sc.nextInt());
}
System.out.println("enter which node is connected to last node");
node = sc.nextInt();
createaloop(head, node);
System.out.println("output--> " + detectloop());
}
}