-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist_3
More file actions
77 lines (65 loc) · 1.66 KB
/
linkedlist_3
File metadata and controls
77 lines (65 loc) · 1.66 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
Write a C++ program to insert a new node at the middle of a given Singly Linked List.
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
int size = 0;
void insert(Node** head, int data){
Node* new_Node = new Node();
new_Node->data = data;
new_Node->next = *head;
*head = new_Node;
size++;
}
void insert_middle(Node** head, int data){
Node* new_Node = new Node();
new_Node->data = data;
if(*head == NULL){
new_Node->data = data;
new_Node->next = *head;
*head = new_Node;
size++;
return;
}
Node* temp = *head;
// Find insertion position for middle
int mid = (size % 2 == 0) ? (size/2) : (size+1)/2;
while(--mid){
temp = temp->next;
}
new_Node->next = temp->next;
temp->next = new_Node;
size++;
}
//Display all nodes
void display_all_nodes(Node* node)
{
while(node!=NULL){
cout << node->data << " ";
node = node->next;
}
}
int main()
{
Node* head = NULL;
insert(&head,1);
insert(&head,3);
insert(&head,5);
insert(&head,7);
cout << "Original list:\n";
display_all_nodes(head);
cout << "\nSingly Linked List: after insert 9 in the middle of the said list-\n";
insert_middle(&head, 9);
display_all_nodes(head);
cout << "\nSingly Linked List: after insert 11 in the middle of the said list-\n";
insert_middle(&head, 11);
display_all_nodes(head);
cout << "\nSingly Linked List: after insert 13 in the middle of the said list-\n";
insert_middle(&head, 13);
display_all_nodes(head);
cout<<endl;
return 0;
}