我有我創建的代碼鏈接列表C. signly鏈表如下問題:指針的單鏈表指針用C
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node *mknode(int data)
{
struct node* np=malloc(sizeof(struct node));
np->data=data;
np->next=NULL;
return np;
}
struct node * insert (struct node* list,int data)
{
struct node *np;
struct node*curr=list;
struct node* prev=NULL;
np=mknode(data);
for(;curr &&data<curr->data;curr=curr->next)
prev=curr;
np->next=curr;
if(prev)
prev->next=np;
else
list=np;
return list;
}
int main()
{
struct node* head;
head=malloc(sizeof(struct node));
head=insert(head,7);
head=insert(head,2);
head=insert(head,4);
printf("%d",head->data);
printf("%d",head->next->data);
printf("%d",head->next->next->data);
return 0;
}
然而,當我互聯網上搜索,我意識到,雙指針用於創建鏈表而不是普通指針。我的意思是,struct node **list
,而不是struct node * list
。我想知道爲什麼 ?哪一個是正確的,如果他們兩個都是真的,他們之間有什麼區別,我用我在這裏寫的示例主實現了我的實現,它工作正常,但我不知道爲什麼我應該使用指針指針?提前致謝。
'head = malloc(sizeof(struct node));'頭部未正確初始化。 – BLUEPIXY
@PeterMiehle我不認識的問題,你鏈接here.Sorry重複的,但我沒有做重複的目的 – caesar