Sign in to follow this  
300Thousand

[C]Need help with deleting at head function in linked list

Recommended Posts

Hello i have a program where i needed to add 3 functions to it.

sum up elements, insert at end and delete at front. The rest was already written from my teacher.

Now i could do the first 2 functions they are in bottom of the code but i dont know how i could do the last function.

the last function is under the main function i tried some shit but thats soooooo wrong.

Some text is on german but you should still understand everything

Pls help me 

Here is the code:

 

#include 
#include 

struct node {
int number;
struct node *next;
};

struct node *insert_at_head(int x, struct node *list);

void display_list(struct node *list);

int sum_up_elements(struct node *list);

struct node *insert_at_tail(int x, struct node *list);


int main() {
struct node *my_list = NULL;

my_list = insert_at_head(3, my_list);

my_list = insert_at_tail(15, my_list);

my_list = insert_at_tail(-4, my_list);

my_list = insert_at_tail(99, my_list);
display_list(my_list);
 printf("the sum of the elements: %d\n",sum_up_elements(my_list));
return(0);
}
struct node *delete_at_head(struct node *z){
struct node *current_node;
struct node *previous_node;
if(z==NULL){
 printf("Liste ist empty\n");
}
else
current_node=z;
z=z->next;
printf("%d got deleted",current_node->number);
free(current_node);

}
struct node *insert_at_head(int x, struct node *z) {
struct node *new_node = malloc(sizeof(struct node));
if (new_node == NULL) {
printf("Fehler bei der Speicherallokation\n");
return(NULL);
}
new_node->number = x;
new_node->next = z;
return(new_node);
}
void display_list(struct node *z) {
while (z != NULL) {
printf("%d ", z->number);
z = z->next;
}
printf("\n");
}
int sum_up_elements(struct node *z) {
int sum=0;
 for(;z->next!=NULL;z=z->next){
   sum +=z->number;
 }
 return(sum);
}

struct node *insert_at_tail(int x, struct node *list) {
struct node *new_node=malloc(sizeof(struct node));
if(new_node==NULL){
 printf("Fehler bei der Speicherallokation\n");
 return(NULL);
}
new_node->number=x;
new_node->next=NULL;
if(list==NULL) return(new_node);
struct node *head=list;
while(list->next!=NULL) list=list->next;
list->next=new_node;


return(head);
}

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this