簡體   English   中英

如何更改 function 內的節點指向的位置

[英]How can I change where a node points inside a function

我想創建一個 function 在鏈表中搜索某個值,然后將包含它的節點和包含它的節點放在兩個單獨的節點中。 這是我的代碼,我不知道為什么它不起作用:

#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);
}

謝謝 !

您想將 R 和 RA 的地址傳遞給 find_node。 並將參數聲明為**

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

然后在 function 中使用 ( *R / *RA )

打電話給

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

在您的版本中, find_node 無法重新分配傳入的指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM