C语言建立链表的操作
程序员文章站
2024-02-11 13:45:04
...
尾插法建立带头结点的单链表
#include<stdio.h>
#include<stdlib.h>
typedef struct Linklist{
int data;
struct Linklist *next;
}Node;
Node *Creat(){
Node *Head;
Node *pNew,*r;
int x;
Head = (Node*)malloc(sizeof(Node));
Head->next = NULL;
r = Head;
scanf("%d",&x);
while (x != -1){
pNew =(Node*)malloc(sizeof(Node));
pNew->data = x;
r->next = pNew;//关键代码
r = pNew;
scanf("%d",&x);
}
r->next = NULL;
return Head;
}
void Output(Node *Head){
Node *p;
p = Head->next;
while (p){
printf("%d\n",p->data);
p = p->next;
}
}
int main(void){
Node *Head;
printf("开始建立单链表L,输入-1结束: \n");
Head = Creat();
Output(Head);
return 0;
}
头插法建立带头结点的单链表
#include<stdio.h>
#include<stdlib.h>
typedef struct Linklist{
int data;
struct Linklist *next;
}Node;
Node *Creat(){
Node *Head;
Node *pNew;
int x;
Head = (Node*)malloc(sizeof(Node));
Head->next = NULL;
scanf("%d",&x);
while(x != -1){
pNew = (Node*)malloc(sizeof(Node));
pNew->data = x;
pNew->next = Head->next;
Head->next = pNew;
scanf("%d",&x);
}
return Head;
}
void Output (Node *Head){
Node *p;
p = Head->next;
while(p){
printf("%d\n",p->data);
p = p->next;
}
}
int main(void){
Node *Head;
printf("开始建立单链表L,输入-1结束: \n");
Head = Creat();
Output(Head);
return 0;
}