Linked List Lastly
kaziamir
c_cpp
a year ago
1.9 kB
10
Indexable
Never
#include<bits/stdc++.h> using namespace std; #define resetP p=start typedef struct node{ int data; struct node *next; }node; void output(node *x){ while(x != NULL){ cout<<x->data<<" "; x = x->next; } cout<<endl; } void solution(){ int n; cin>>n; node *nodes[n]; for(int i=0;i<n;i++){ nodes[i] = (node *)malloc(sizeof(node)); cin>>nodes[i]->data; } for(int i=0;i<n;i++){ if(i == n-1) nodes[i]->next = NULL; else nodes[i]->next = nodes[i+1]; } node *start = nodes[0]; node *p = start; node *to_free = start; /*****Before Any Operation*****/ cout<<"Before any Operation: "<<endl; resetP; output(p); /*****Deleting First Node*****/ /* cout<<"After Deleting First Node: "<<endl; start = start->next; free(to_free); resetP; output(p); */ /*****Deleting Last Node*****/ /* resetP; while((p->next)->next != NULL){ p = p->next; } free(p->next); p->next = NULL; cout<<"After Deleting Last Node: "<<endl; resetP; output(p); */ /*****Deleting Random Node k*****/ cout<<"position: "<<endl; int k; cin>>k; /* for(int i=1;i<k-1;i++){ if(p->next != NULL){ p = p->next; } } to_free = p->next; p->next = p->next->next; free(to_free); cout<<"After Deleting Node: "<<k<<endl; resetP; output(p); */ node *newNode; newNode = (node *)malloc(sizeof(node)); cout<<"New Node Data: "<<endl; cin>>newNode->data; resetP; for(int i=1;i<k-1;i++){ if(p->next != NULL){ p = p->next; //cout<<p->data<<endl; } } //cout<<p->data<<endl; newNode->next = p->next; p->next = newNode; cout<<"New List: "<<endl; resetP; output(p); } int main(){ solution(); return 0; }