简体   繁体   中英

How can I change where a node points inside a function

I want to create a function that search for a certain value in a linked list and then put the node containing it and the node before the one containing it in two separate nodes. This is my code and I can't figure out why it does not work:

#include <stdio.h>
#include <stdlib.h>

struct node{
    int val;
    struct node* next;
};
typedef struct node node_t;

void printlist(node_t *head){
    node_t *temp=head;

    while (temp!=NULL){
        printf("%d -",temp->val);
        temp=temp->next;
    }
    printf("\n");
}
node_t *create_new_node(int value){
    node_t *result=malloc(sizeof(node_t));
    result->val=value;
    result->next=NULL;
    return result;
}



void *insert_after_node(node_t *node_to_insert,node_t *newnode){
    newnode->next=node_to_insert->next;
    node_to_insert->next=newnode;
}

void *find_node(node_t *head,int value,node_t *R,node_t *RA){
    node_t *tmp=head;
    while (R!=NULL && tmp!=NULL){
        if (tmp->val==value)
            R=tmp;
        else{
            RA=tmp;
            tmp=tmp->next;
        }
    }
}

int main(){
    node_t *head=NULL;
    node_t *tmp;
    node_t *R=NULL;
    node_t *RA=NULL;
    for (int i=0;i<25;i++){
        tmp=create_new_node(i);
        insert_at_head(&head,tmp);
    }

    find_node(head,13,R,RA);
    printlist(head);
    printlist(RA);
    printlist(R);
}

Thank you !

You want to pass in the addresses of R and RA to find_node. And declare the params as **

void *find_node(node_t *head,int value,node_t **R,node_t **RA){

and then use ( *R / *RA ) in the function

Call with

find_node(head,13,&R,&RA);

In your version, find_node cannot reassign the pointers passed in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM