#include<stdio.h>
#include<malloc.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void print(struct LNode* L)
{
L=L->next;
while(L)
{
printf("%d ",L->data);
L=L->next;
}
printf("\n");
}
LinkList List_HeadInsert(LinkList &L){
LNode *s;
int x;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
int main(){
LNode headNode;
headNode.next = NULL;
LinkList L;
L = &headNode;
printf("请输入单链表的值:");
List_HeadInsert(L);
print(L);
return 0;
}
流程:先定义一个头结点跟一个单链表,将头结点置为空,将单链表指向头结点。然后执行头插函数:
LinkList List_HeadInsert(LinkList &L){
LNode *s;
int x;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
插入完成后,输出单链表,执行输出函数:
void print(struct LNode* L)
{
L=L->next;
while(L)
{
printf("%d ",L->data);
L=L->next;
}
printf("\n");
}