链表:插入后如何return整个链表

linked list: how to return the whole linked list after insterting

我正在尝试 return 在下面程序的 Insert 函数中链表的头部。但是,它因编译错误而失败。 谁能告诉我我做错了什么:

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

struct ListNode
{
    int data;
    struct ListNode *next;
};


int ListLength(struct ListNode *head)
{
    int count = 0;
    struct ListNode *temp=head;
    while(temp!=NULL)
    {
        count++;
        temp=temp->next;
    }
    return count;
}

struct ListNode *Insert(struct ListNode *head, int value, int pos)
{
    struct ListNode *temp,*curr;
    curr=head;
    int k=1;
    temp=(struct ListNode *)malloc(sizeof(struct ListNode));
    if(pos==1)
    {
        temp->data=value;
        if(head==NULL)
        {
            temp->next=NULL;
            head=temp;
        }
        else
        {
            temp->next=head;
            head=temp;
        }
    }
    else
    {
        while((curr!=NULL) && (k<pos))
        {
            k++;
            curr=curr->next;
        }
        temp->data=value;
        temp->next=curr->next;
        curr->next=temp;

    }
    return head;
}
void printList(struct ListNode *head)
{
    struct ListNode *temp;
    temp=head;
    while(temp!=NULL)
    {
        printf("%d",temp->data);
        printf(" ");
        temp=temp->next;
    }
}
int main
{
    struct ListNode *head=NULL;
    //head = NULL;
    head=Insert(head,10,1);
    //Insert(head,11,2);
    printList(head);

    return 0;
}

我正在尝试return插入后的新链表的头部。我不知道我哪里错了。在此先感谢您的帮助。

(i) 首先,包括评论中提到的 int main(void)

(ii) 接下来,使用您当前的代码,当您尝试打印列表时,您将陷入无限循环并导致堆栈溢出。

为避免这种情况,在每次打印后递增 temp 以指向下一个节点。

因此您的打印函数应该如下所示:

void printList(struct ListNode *head)
{
    struct ListNode *temp;
    temp=head;
    while(temp!=NULL)
    {
        printf("%d",temp->data);
        printf(" ");
        temp=temp->next; // this line is required
    }
}

(iii) 在您的主函数中,使用参数调用 printList,即节点的头部,如下所示:

printList(head);

(iv) 不要忘记在查找列表函数的长度时 return count。在 ListLength 函数的末尾添加 return 语句:

return count;

(v) 当前代码无法处理 head 为 NULL 且用户希望在大于 1 的位置插入的情况。或者更一般地说,当用户希望在某个位置插入时大于当前列表的长度。

虽然您相信不会给出这样的输入,但始终会处理此类异常(在尝试访问空节点的内存时,您可能会在此处得到 SEGMENTATION FAULT)。

要处理这个问题,您可以在 Insert 函数的开头添加一个检查,例如,

int lenList = ListLength(head);
if (lenList < pos)
    {
        printf("Please provide a position less than %d to insert", lenList);
        return 0; // don't proceed with inserting node with NULL pointers
    }

如果 head 被声明为全局的,则您不必 return 它。 (对不起,我的回答很短)