-
Notifications
You must be signed in to change notification settings - Fork 45
/
insertAtMiddle.cpp
53 lines (49 loc) · 949 Bytes
/
insertAtMiddle.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
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
Node *prev;
};
void insertAtHead(Node **head_ref ,int mydata)
{
Node* temp=new Node();
temp->data=mydata;
temp->next=*head_ref;
temp->prev=NULL;
if(*head_ref!=NULL)
{
(*head_ref)->prev=temp;
}
(*head_ref)=temp;
}
void insertAtMiddle(Node *previous,int mydata)
{
Node *temp=new Node();
temp->data=mydata;
temp->next=previous->next;
temp->prev=previous;
previous->next=temp;
if(temp->next!=NULL)
{
temp->next->prev=temp;
}
}
void print(Node *head)
{
Node*temp=head;
while( temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main(){
Node *head=NULL;
insertAtHead(&head,2);
insertAtHead(&head,5);
insertAtHead(&head,8);
insertAtMiddle(head->next,10);
print(head);
return 0;
}