C 在链表的开头添加元素
我不明白为什么这个函数不在链表的开头添加元素。头部保持不变C 在链表的开头添加元素,c,linked-list,insert,C,Linked List,Insert,我不明白为什么这个函数不在链表的开头添加元素。头部保持不变 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: ");
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;
}
你需要改变
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
}
你需要改变
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
}
您可以使用指针对指针来处理该问题。 您还可以返回new begin from start()
您可以使用指针对指针来处理该问题。 您还可以返回new begin from start()
您从不更新列表头,因此在调用后它仍然指向旧的列表头。您需要将新的头返回给调用者(或者向
头添加一个间接级别,并通过指针将其更改)。您永远不会更新列表头,因此在调用后它仍然指向旧的列表头。你需要将新的头返回给调用者(或者向头添加一个间接级别,并通过指针将其更改)。我用“return”完成了,但我想用指针指向指针,你能更好地解释一下吗?我认为使用return方法可以向头添加常量限定符,它可以保证更少的副作用。我用“return”完成了但我想使用指针对指针,你们能解释得更好吗?我认为使用返回方法可以在头上添加常量限定符,它可以保证更少的副作用。
node *new_begin(const node *head) {
node *new = malloc(sizeof(node));
/* add new node information */
return new;
}