forked from hariom20singh/data-structure-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertAtEnd.cpp
More file actions
78 lines (71 loc) · 1.36 KB
/
insertAtEnd.cpp
File metadata and controls
78 lines (71 loc) · 1.36 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
78
#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 insertAtEnd(Node **head_ref,int mydata)
{
Node* last=*head_ref;
Node* newNode=new Node();
newNode->data=mydata;
newNode->next=NULL;
if((*head_ref)==NULL)
{
newNode->prev=NULL;
*head_ref=newNode;
return;
}
while(last->next!=NULL)
{
last=last->next;
}
last->next=newNode;
newNode->prev=last;
return;
}
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);
insertAtEnd(&head,12);
insertAtEnd(&head,15);
print(head);
return 0;
}