【问题标题】:Add element at the beginning of linked list在链表的开头添加元素
【发布时间】:2020-04-23 03:01:41
【问题描述】:

我不明白为什么这个函数没有在链表的开头添加元素。头部保持不变。

typedef struct node_struct{
    int data;
    struct node_struct *next;
}node;

void beginning(node *head){
     node *new = malloc(sizeof(node));
     int value;
     printf("Insert a number to add at the beginning: ");
     scanf("%d",&value);
     new->data = value;
     new->next = head;
}

【问题讨论】:

  • 你永远不会更新列表头,所以在调用之后它仍然指向旧的列表头。您需要将新的头部返回给调用者(或向head 添加一个间接级别并通过指针更改它)。

标签: c linked-list insert


【解决方案1】:

你需要改变

void beginning(node *head){ 

到

void beginning(node **head){

这是我的代码:

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


typedef struct NODE{
    int data;
    struct NODE *next;
}node;

typedef struct NODE *Tode;
void create(Tode *head){

     *head = malloc(sizeof(node));
     (*head)->next = NULL;
}
void beginning(Tode *head, int numSize){
    Tode new;
    int value, i;
    for(i = 0; i < numSize; i++){
        new = malloc(sizeof(node));
        scanf("%d",&value);
        new->data = value;
        new->next = (*head)->next;
        (*head)->next = new;
    }
}
void printList(Tode head){
    Tode ptr;
    ptr = head->next;
    printf("\nprint List's value\n");
    while(ptr){
        printf("%d ",ptr->data);
        ptr = ptr->next;
    }
    printf("\n");
}
int main(){
    node *head;
    int numSize;
    create(&head);
    printf("Insert how many  number to add at the beginning: ");
    scanf("%d",&numSize);
    beginning(&head, numSize);
    printList(head);
    // delete(&head);        // youself do
}

运行结果:

Insert how many  number to add at the beginning: 5
1 3 6 8 235

print List's value
235 8 6 3 1 

【讨论】:

    【解决方案2】:

    您可以使用指向指针的指针来处理问题。 你也可以从开始()返回新的开始。

    node *new_begin(const node *head) {
        node *new = malloc(sizeof(node));
        /* add new node information */
        return new;
    }
    

    【讨论】:

    • 我是用“return”做的,但我想用指针指向指针,你能解释一下吗?
    • 我认为使用return方法可以在head中添加const限定符,它可以保证更少的副作用。
    猜你喜欢
    • 2021-04-16
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 2021-06-28
    相关资源
    最近更新 更多