to delete a node using one pointer
my code looks like this:
Expand|Select|Wrap|Line Numbers
- #include <stdio.h>
- #include <stdlib.h>
- struct node{
- int first ;
- struct node *next ;
- } ;
- struct node *add_to_list(struct node *lst, int n){
- struct node *newnode ;
- newnode = malloc(sizeof(struct node)) ;
- if(newnode == NULL){
- printf("malloc failed to add\n") ;
- exit(EXIT_FAILURE) ;
- }
- newnode->first = n ;
- newnode->next = lst ;
- return newnode ;
- }
- void free_list(struct node *lst) {
- struct node *p;
- while (lst != NULL) {
- p = lst->next;
- free(lst);
- lst = p;
- }
- }
- void print_list(struct node *lst) {
- struct node *p;
- printf("( ");
- for (p = lst; p != NULL; p = p->next)
- printf("%d ", p->first);
- printf(")\n");
- }
- //use only one pointer!
- struct node * delete_from_list(struct node *lst, int key){
- struct node *temp ;
- struct node *helper ;
- if(lst == NULL)
- return NULL ;
- if(lst->first == key){
- temp = lst ;
- lst = lst->next ;
- free(temp) ;
- return lst ;
- }
- for(temp = lst ; temp != NULL && temp->first != key ; temp = temp->next){
- ;
- }
- printf("%d\n",temp->first) ;
- if (temp == NULL) // key is not in the lst
- return NULL ;
- if (temp->first == key){
- temp = temp->next ;
- return lst ;
- }
- helper = temp->next ;
- temp->next = helper->next ;
- //temp->next = temp->next->next ;
- free(helper) ;
- return lst ;
- }
- int main(void){
- struct node *l = NULL ;
- l = add_to_list(l,56) ;
- l = add_to_list(l,45) ;
- l = add_to_list(l,5) ;
- l = add_to_list(l,2) ;
- print_list(l) ;
- l = delete_from_list(l,5) ;
- print_list(l) ;
- free_list(l) ;
- return 0 ;
- }
if the list is empty (NULL),
contains one element 4,NULL ;
but when i try to pass a list 2,5,45,56, NULL and delete
5 it just returns the whole list
help?
i don't really know if there is a way to use only 1 pointer - so i used 2
thanks in advance