如何返回链表中的结构体节点指针

问题描述 投票:0回答:1
int position(int key)
{
 struct node *new=(struct node*)malloc(sizeof(struct node));
 struct node *p1=head;
 while(p1->info!=key&&p1->link!=NULL)
 p1=p1->link;

 return struct node *p1;
}

void insertafter()
{
 struct node *new=(struct node*)malloc(sizeof(struct node));
 struct node *p1=head;
 p1=position();
}

我想将函数position中p1的值返回给insertafter()。那么position的返回类型是什么,因为它返回一个结构体节点,我应该如何给出return语句。 键是我必须在其后插入新节点的值。

c function return nodes singly-linked-list
1个回答
0
投票

看来您走在正确的道路上!不过,还有一些地方需要修正。

position
函数中,您应该处理
head
NULL
时的情况,以避免取消引用空指针。此外,您不需要在此函数中为
new
分配内存。这是更正后的
position
函数:

    struct node* position(int key)
    {
        struct node *p1 = head;
    
        while (p1 != NULL && p1->info != key)
            p1 = p1->link;
    
        return p1;
    }

insertafter
函数中,确保处理
position
返回
NULL
(表示未找到密钥)的情况。另外,在使用
new
之前为其分配内存也很重要。这是更正后的
insertafter
函数:

    void insertafter(int key)
    {
        struct node *new = (struct node*)malloc(sizeof(struct node));
        if (new == NULL) {
            perror("Memory allocation failed");
            exit(EXIT_FAILURE);
        }
    
        struct node *p1 = position(key);
    
        if (p1 != NULL) {
            new->link = p1->link;
            p1->link = new;
        }
        else {
            printf("Key not found in the linked list.\n");
            free(new); // Free the allocated memory
        }
    }

确保在实际代码中正确处理内存分配和释放。另外,正确初始化

head
并考虑列表为空的情况。

© www.soinside.com 2019 - 2024. All rights reserved.