#include <stdio.h>
#include<malloc.h>
//定义结点结构体
typedef struct node{
char data;
struct node *next;
}NODE,*JD;//定义一个NODE结构体类型和一个JD结构体类型指针
//建链表函数 head为头指针结点
void insertNode(JD *head,char ch){
JD temp;//定义一个临时变量
JD p=(JD)malloc(sizeof(NODE));
p->data=ch;
p->next=NULL;
//判断head结点是否为空,head为空那么就是空链表
if(NULL==*head){
*head=p;
printf("插入头节点成功\n");
}else{
temp=*head;
//temp指向链表尾
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=p;
printf("插入尾节点成功\n");
}
}
int coutLength(JD head){
int length=0;
while(head!=NULL){
length++;
//printf("++%c++",head->data);
head=head->next;
}
return length;
}
int main(){
JD head=NULL;
printf("请输入字符:\n");
char ch;
while((ch=getchar())!='$'){
insertNode(&head,ch);//此处传递指针地址给指针的指针!!!
fflush(stdin);//清楚缓存
}
int length=coutLength(head);
printf("链表长度为:%d\n",length);
while(head!=NULL) {
printf("%c ",head->data);
head=head->next;
}
}
尾插法建链表
最新推荐文章于 2022-05-11 23:12:22 发布