Please I need someone help. I’m having trouble with my homework.
This homework is very simple. Create a list(1,2,3) and delete the middle number by creating a function delnode. But it must use the function free().
Right now,I have created the list (1,2,3) by using linked list method. I want to delete the number 2 but it doesn’t work. It should be comes out with (1,3) but it comes out with (2,3).
#include <stdio.h>
#include <stdlib.h>
struct node{
int number;
struct node* next;
};
typedef struct node node;
//prototype function
node* allocateMemory(void);
node* insertNode(node*);
void delnode(node*);
int main(){
int i,num;
node* entr = allocateMemory();
node* p = NULL;
entr->number = 1;
entr->next = NULL;
num = 3;
for(i=1;i<num;i++){
if(!p){
p=insertNode(entr);
}else{
p=insertNode(p);
}
p->number = i+1;
}
while(entr){
if(entr->number == 2){
entr->number == NULL;
break;
}
entr=entr->next;
}
while(entr){
printf("%d\n",entr->number);
entr=entr->next;
}
return 0;
}
node* insertNode(node* current){
node* newNode = allocateMemory();
current->next = newNode;
newNode->next = NULL;
return newNode;
}
void delnode(node* current){
node* temp = allocateMemory();
temp = current->next->next;
free(current->next);
current = temp;
free(temp);
return ;
}
node* allocateMemory(void){
return (node*)malloc(sizeof(node));
}
Ok, this function
delnodeis all kinds of messed up. You don’t need to allocate more memory when you’re trying to delete a node. You need to link the previous to the next, and delete the current.It should look more like this.
If you’re trying to add three nodes, you need to change your loop.
If you want to delete the node with
numberof2: