Skip to content

Commit f6f7122

Browse files
committed
adding the middle node program
1 parent 00d57e1 commit f6f7122

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

middleNodeLL.java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.io.*;
2+
class LinkedList {
3+
Node head;
4+
5+
class Node {
6+
int data;
7+
Node next;
8+
Node(int d)
9+
{
10+
data = d;
11+
next = null;
12+
}
13+
}
14+
15+
void printMiddle()
16+
{
17+
Node slow_ptr = head;
18+
Node fast_ptr = head;
19+
20+
while (fast_ptr != null && fast_ptr.next != null) {
21+
fast_ptr = fast_ptr.next.next;
22+
slow_ptr = slow_ptr.next;
23+
}
24+
System.out.println("The middle element is ["
25+
+ slow_ptr.data + "] \n");
26+
}
27+
28+
public void push(int new_data)
29+
{
30+
Node new_node = new Node(new_data);
31+
32+
new_node.next = head;
33+
34+
head = new_node;
35+
}
36+
public void printList()
37+
{
38+
Node tnode = head;
39+
while (tnode != null) {
40+
System.out.print(tnode.data + "->");
41+
tnode = tnode.next;
42+
}
43+
System.out.println("NULL");
44+
}
45+
46+
public static void main(String[] args)
47+
{
48+
LinkedList llist = new LinkedList();
49+
for (int i = 5; i > 0; --i) {
50+
llist.push(i);
51+
llist.printList();
52+
llist.printMiddle();
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)