Skip to content

Commit 34f94d8

Browse files
authored
Delete Middle of Linked List.cpp
1 parent e3d26b9 commit 34f94d8

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
struct Node
5+
{
6+
int data;
7+
struct Node* next;
8+
9+
Node(int x){
10+
data = x;
11+
next = NULL;
12+
}
13+
};
14+
15+
/* Function to get the middle of the linked list*/
16+
struct Node *deleteMid(struct Node *head);
17+
void printList(Node* node)
18+
{
19+
while (node != NULL) {
20+
cout << node->data <<" ";
21+
node = node->next;
22+
}
23+
cout<<"\n";
24+
}
25+
int main()
26+
{
27+
int t;
28+
cin>>t;
29+
while(t--)
30+
{
31+
int n;
32+
cin>>n;
33+
34+
int data;
35+
cin>>data;
36+
struct Node *head = new Node(data);
37+
struct Node *tail = head;
38+
for (int i = 0; i < n-1; ++i)
39+
{
40+
cin>>data;
41+
tail->next = new Node(data);
42+
tail = tail->next;
43+
}
44+
head = deleteMid(head);
45+
printList(head);
46+
}
47+
return 0;
48+
}
49+
50+
51+
// } Driver Code Ends
52+
53+
54+
55+
/* Link list Node:
56+
57+
struct Node
58+
{
59+
int data;
60+
struct Node* next;
61+
62+
Node(int x){
63+
data = x;
64+
next = NULL;
65+
}
66+
};
67+
68+
*/
69+
70+
// Deletes middle of linked list and returns head of the modified list
71+
Node* deleteMid(Node* head)
72+
{
73+
// Your Code Here
74+
Node *slow=head, *fast=head, *prev=NULL;
75+
while(fast!=NULL && fast->next!=NULL )
76+
{
77+
prev=slow;
78+
slow=slow->next;
79+
fast=fast->next->next;
80+
}
81+
Node *temp=slow;
82+
prev->next=slow->next;
83+
free(temp);
84+
return head;
85+
}

0 commit comments

Comments
 (0)