-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathak7
72 lines (63 loc) · 1.33 KB
/
ak7
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
// Java program to find middle of linked list
class LinkedList
{
Node head; // head of linked list
/* Linked list node */
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Function to print middle of linked list */
void printMiddle()
{
Node slow_ptr = head;
Node fast_ptr = head;
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.println("The middle element is [" +
slow_ptr.data + "] \n");
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* This function prints contents of linked list
starting from the given node */
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+"->");
tnode = tnode.next;
}
System.out.println("NULL");
}
public static void main(String [] args)
{
LinkedList llist = new LinkedList();
for (int i=5; i>0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}
// This code is contributed by Rajat Mishra