单链表头插法
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList List_HeadInsert(LinkList &l){
LNode *s;
int x;
l=(LinkList)malloc(sizeof(LNode));
l->next=NULL;
scanf("%d",&x);
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));
s->data =x;
s->next=l->next;
l->next=s;
scanf("%d",&x);
}
return l;
}
int main(){
LinkList l;
l=List_HeadInsert(l);
printf("链表元素为:");
LNode *p;
p=l->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
尾插法
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList List_TailInsert(LinkList &l){
int x;
l=(LinkList)malloc(sizeof(LNode));
LNode *s,*r=l; //r表尾指针
scanf("%d",&x);
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return l;
}
int main(){
LinkList l;
printf("尾插法建立单链表,请输入元素:");
l=List_TailInsert(l);
LNode *p;
printf("链表元素为:");
p=l->next;
while(p!=NULL)
{
printf("%d ", p->data);
p = p->next;
}
}