int main() { int i; Node *p = (Node *)malloc(sizeof(Node)), *head = p; // allocate memory for first node and declare second node head (you don't really need it) p->next = NULL; //first node has data 0, next is NULL; p->data = 0; add(head, 10); //2nd node add(head, 20); //3rd node add(head, 80); //4th node; peek(head); printf("\n"); rem(head, 20); //remove node with the data = 20 peek(head); printf("\n"); head = rem2(head, 0); // remove the node with the data = 0 (first node) peek(head); printf("\n"); rem(head, 12); // doesn't do anything peek(head); free(head); free(p); return 0; }
Node* rem2(Node *p, int num){ // second remove function (acts the same as the first) if(p == NULL){ // uses recursion instead then returns the Node printf("Data not found\n"); return NULL; } if(p->data == num){ Node *temp = p->next; free(p); p = temp; return temp; } p-> next= rem2(p->next, num); return p; //must always return the calling pointer and reassign it in main... }
void removee(){ int rem,ind; printf("condition for removing\n1. By index\n2. By value\n") ; scanf("%d",&rem); switch(rem) { case 1: printf("At what index u want to remove"); scanf("%d",&ind); rem1(ind); break; case 2: printf("What value you want to remove"); scanf("%d",&ind); rem2(ind); break; default: break; } }