-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathExercise_3.java
More file actions
85 lines (76 loc) · 2.14 KB
/
Exercise_3.java
File metadata and controls
85 lines (76 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
// Time Complexity :o(n)
// Space Complexity :o(1)
// Did this code successfully run on Leetcode :n/a
// Any problem you faced while coding this :n.a
// Your code here along with comments explaining your approach
//Iterate over linklist and find length of linkedList
//iterate till half of linkedlist and inittialize temp node to head and move temparary node foward.
//once temparary node reached at half of linkedlist, return temparary node
class LinkedList
{
Node head; // head of linked list
/* Linked list node */
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public int getLen(){
int length =0;
Node temp = head;
while(temp!=null){
length++;
temp = temp.next;
}
return length;
}
/* Function to print middle of linked list */
//Complete this function
void printMiddle()
{
//Write your code here
//Implement using Fast and slow pointers
if(head!=null){
int length = getLen();
Node temp = head;
int middleLength = length/2;
while(middleLength!=0){
temp = temp.next;
middleLength--;
}
System.out.println("The middle element is [" + temp.data + "]");
System.out.println("\n\n");
}
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_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=15; i>0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}