#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value)
{
data = value;
next = nullptr;
}
};
Node* insertAtPosition(Node* head, int position, int data) {
Node* newNode = new Node(data);
if (position == 1) {
newNode->next = head;
head = newNode;
return head;
}
Node* current = head;
for (int i = 1; i < position - 1 && current != nullptr;
++i) {
current = current->next;
}
if (current == nullptr) {
cout << "Position is out of bounds." << endl;
delete newNode;
return head;
}
newNode->next = current->next;
current->next = newNode;
return head;
}
Node* deleteNode(Node* head, int position)
{
Node* prev;
Node* temp = head;
if (temp == NULL)
return head;
if (position == 1) {
head = temp->next;
return head;
}
for (int i = 1; i != position; i++) {
prev = temp;
temp = temp->next;
}
if (temp != NULL) {
prev->next = temp->next;
free(temp);
}
else {
cout << "Data not present\n";
}
return head;
}
void printList(Node* head){
while (head != nullptr) {
cout << head->data << " ";
head = head->next;
}
}
int main(){
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
cout << "linked List : ";
printList(head);
int n;
string s="\n\n1.insertion,\n2.deletion,\nchoose any: ";
while(cout<<s,cin>>n)
{
int data,pos;
cout<<"\nPosition: ";
cin>>pos;
(n-1)? (head = deleteNode(head, pos)):(cout<<"\nData: ",cin>>data,head = insertAtPosition(head, pos, data));
cout << "\nlinked List : ";
printList(head);
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwpzdHJ1Y3QgTm9kZSB7CiAgICBpbnQgZGF0YTsKICAgIE5vZGUqIG5leHQ7CiAgICBOb2RlKGludCB2YWx1ZSkKICAgIHsKICAgICAgICBkYXRhID0gdmFsdWU7CiAgICAgICAgbmV4dCA9IG51bGxwdHI7CiAgICB9Cn07CgpOb2RlKiBpbnNlcnRBdFBvc2l0aW9uKE5vZGUqIGhlYWQsIGludCBwb3NpdGlvbiwgaW50IGRhdGEpIHsKICAgIE5vZGUqIG5ld05vZGUgPSBuZXcgTm9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