-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGFG LL-1 middleElement.cpp
89 lines (74 loc) · 1.51 KB
/
GFG LL-1 middleElement.cpp
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
87
88
89
#include <stdio.h>
#include <iostream>
#include <bits/stdc++.h>
#include <map>
#include <string.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *head= NULL;
void newnode(int t) //nodes are added at the front of the LL. So, if the input is 1 2 3 4, they are stored as 4 3 2 1 [1 is stored first and 4 is stored last]
{
struct node *temp = new node;
temp->data = t;
temp-> next = head;
head = temp;
}
void getmiddle()
{
struct node *slow,*fast;
slow = head; fast = head;
while(fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
cout <<"Middle Element is " << slow->data << endl;
}
void reversell()
{
struct node *prev,*curr,*temp;
curr=head;
prev=NULL;
while(curr!=NULL)
{
temp=curr->next;
curr->next = prev;
cout << curr-> data << "rev " << curr->next->data << endl ;
prev=curr;
curr=temp;
}
head = prev;
curr = head;
while(curr!=NULL)
{
cout << curr->data << " ";
curr=curr->next;
}
// return prev;
}
int main()
{
struct node *curr;
int n,t;
cin >> n;
for (int i=0;i<n;i++)
{
cin >> t;
newnode(t);
//curr=curr->next;
}
curr=head;
while(curr!=NULL)
{
cout << curr->data << " ";
curr=curr->next;
}
cout << endl;
getmiddle();
reversell();
return 0;
}