forked from rathoresrikant/HacktoberFestContribute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDelete_middle_element_ll.cpp
76 lines (64 loc) · 1.13 KB
/
Delete_middle_element_ll.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
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
struct Node* deleteMid(struct Node *head)
{
if (head == NULL)
return NULL;
if (head->next == NULL)
{
delete head;
return NULL;
}
struct Node *slow_ptr = head;
struct Node *fast_ptr = head;
struct Node *prev;
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
prev = slow_ptr;
slow_ptr = slow_ptr->next;
}
prev->next = slow_ptr->next;
delete slow_ptr;
return head;
}
void printList(struct Node *ptr)
{
while (ptr != NULL)
{
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL\n";
}
Node *newNode(int data)
{
struct Node *temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
int main()
{
int c;
cin>>c;
struct Node* head = newNode(c);
struct Node* head2=head;
while(c!=-1)
{
cin>>c;
head2->next = newNode(c);
head2=head2->next;
}
cout << "Given Linked List\n";
printList(head);
head = deleteMid(head);
cout << "Linked List after deletion of middle\n";
printList(head);
return 0;
}