如何在C语言中实现单链表
我试图用C来填充我的链表,但id并没有说明如何填充 我想。我想保留一个指针“p”,并用同一个指针继续添加到列表中。但是,当我尝试打印时,它只打印头部的数据如何在C语言中实现单链表,c,struct,linked-list,nodes,singly-linked-list,C,Struct,Linked List,Nodes,Singly Linked List,我试图用C来填充我的链表,但id并没有说明如何填充 我想。我想保留一个指针“p”,并用同一个指针继续添加到列表中。但是,当我尝试打印时,它只打印头部的数据 #include<stdio.h> #include <stdlib.h> typedef struct{ int data; struct node *next; }node; int main(){ node *head = NULL; head = malloc(sizeof(node
#include<stdio.h>
#include <stdlib.h>
typedef struct{
int data;
struct node *next;
}node;
int main(){
node *head = NULL;
head = malloc(sizeof(node));
if(head==NULL){
printf("ta foirer quelque chose frero!");
return 1;
}
(*head).data=3;
(*head).next=NULL;
node *p = NULL;
p = (node*) head->next;
p = malloc(sizeof(node));
p->data = 5;
p->next = NULL;
p= (node *)p->next;
int i=0;
while(i<5){
p = malloc(sizeof(node));
i++;
p->data = i;
p->next=NULL;
p= (node *)p->next;
}
p = head;
while(p){
printf("\n%d",p->data);
p =(node*) p->next;
}
return 0;
}
我期待着得到更多
3
5
0
1
2
3
4
#包括
#包括
结构节点{
int数据;
结构节点*下一步;
};
typedef结构节点;
无效插入(节点*h,整数v){
节点*tmp=h;
while(tmp->next)
tmp=tmp->next;
node*newnode=malloc(sizeof(node));
newnode->data=v;
newnode->next=NULL;
tmp->next=newnode;
}
int main(){
node*head=NULL;
head=malloc(sizeof(node));
if(head==NULL){
printf(“他选择了弗雷罗!”;
返回1;
}
头部->数据=3;
head->next=NULL;
node*p=NULL;
插入(头,5);
int i=0;
while(idata);
p=p->next;
}
返回0;
}
如果您注意到了,我对代码的布局做了一些修改,使它更干净。您所需要的是遍历以找到出现在添加新节点的位置之前的节点,在本例中即为结束。通常,这是另一个结构中包含头的单独指针,称为链表的尾。您只是没有跟踪位置,无法真正添加节点。上面的这个插入函数就是这样做的。如果你保持一个指向
尾的指针(结束节点),你就不必每次插入新节点时都在列表上迭代了:)
是的,我并没有完全解释所有的事情,希望他能走自己的路,弄清楚尾是用来做什么的。
3
5
0
1
2
3
4
#include<stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
typedef struct Node node;
void insert(node* h, int v) {
node* tmp = h;
while(tmp->next)
tmp = tmp->next;
node* newnode = malloc(sizeof(node));
newnode->data = v;
newnode->next = NULL;
tmp->next = newnode;
}
int main(){
node *head = NULL;
head = malloc(sizeof(node));
if(head==NULL){
printf("ta foirer quelque chose frero!");
return 1;
}
head->data=3;
head->next = NULL;
node *p = NULL;
insert(head, 5);
int i=0;
while(i<5){
insert(head, i++);
}
p = head;
while(p){
printf("%d\n",p->data);
p = p->next;
}
return 0;
}