-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLinsertionatMid.cpp
More file actions
89 lines (71 loc) · 1.45 KB
/
Copy pathLLinsertionatMid.cpp
File metadata and controls
89 lines (71 loc) · 1.45 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
79
80
81
82
83
84
85
86
87
88
89
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data){
this -> data=data;
this -> next = NULL;
}
};
// insert at Head
void insertAtHead(Node* &head, int d){
//first create a new node
Node* temp = new Node(d);
//insert at head
temp -> next = head;
head = temp;
}
//insert at tail
void insertAttail(Node* &tail, int d){
//first create a new node
Node* temp = new Node(d);
//insert at head
tail-> next = temp;
tail = temp;
}
//insert at given pos
void insertAtPos(Node* &head,Node* &tail,int pos, int d){
if(pos==1){
insertAtHead(head, d);
return;
}
Node* temp = head;
int count =1;
while(count<pos-1){
count ++;
temp=temp->next;
}
if(temp->next==NULL){
insertAttail(tail, d);
return;
}
Node* newNodeinsert = new Node(d);
newNodeinsert-> next=temp-> next;
temp->next=newNodeinsert;
}
void printLL(Node* &head){
Node* temp=head;
while(temp!=NULL){
cout<< temp-> data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main(){
// create first node
Node* node1 = new Node(10);
//head pointed to node1
Node* head = node1;
// tail pointed to node1
Node* tail = node1;
//insert at head a new node
insertAttail(tail, 20);
insertAttail(tail, 15);
insertAtPos(head,tail, 4, 34);
//print
printLL(head);
return 0;
}