初始化: headl输入2:ha-bm12 、③ ail tail 输入8:hed-Dm2 tail 每次输入新元素后: 生成新结点;p= malloc((结点大小);p->data=e;p→next=NULL; ②添加到表尾;tail-> next=p 设置新表尾。tail-p;
初始化:head //// ^ 输入2: head //// tail tail 2 ^ p ① ③ ② 每次输入新元素后: • 生成新结点;p=malloc(结点大小); p->data=e; p->next=NULL; ② 添加到表尾;tail->next=p; ③ 设置新表尾。tail=p; head //// tail 8 ^ ① ③ ② 输入8: 2 p
先进先出表的产生过程(1,2,3,40) head 4 0 头指针头结点、 head=malloc(sizeof(struct node)) p=malloc(sizeof(struct node)) tail=head tail->next=p =malloc(sizeof(struct node)) tail=p tail->next=p ail-p tail->next=NULL:
先进先出表的产生过程(1,2,3,4,0): head p /// 1 2 3 4 0 p p p p 头指针 头结点 tail head=malloc(sizeof(struct node)) tail=head tail p=malloc(sizeof(struct node)) tail->next=p tail=p p=malloc(sizeof(struct node)) tail tail->next=p tail=p tail tail tail tail->next=NULL; ^
算法:生成“先进先出”单链表(链式队列) struct Lnode *creatI() struct lnode*head,*tail,*p;//变量说明 int e: head=( struct lnode*) malloc(LENG);//生成表头结点 tail=head: //尾指针指向表头 do{p=( struct lnode米) malloc(LENG);//生成新结点 scanf(%d,&e);/输入一个数 p->data=e //装入输入的元素e tail->next=p //新结点链接到表尾 all-p; //尾指针指向新结点 while(e!=0) //不为0 tail->next=NULL //尾结点的next置为空指针 return head //返回头指针
算法:生成“先进先出”单链表(链式队列) struct Lnode *creat1( ) { struct Lnode *head,*tail,*p; //变量说明 int e; head=(struct Lnode *)malloc(LENG); //生成表头结点 tail=head; //尾指针指向表头 do{ p=(struct Lnode *)malloc(LENG);//生成新结点 scanf(“%d”,&e); //输入一个数 p->data=e; //装入输入的元素e tail->next=p; //新结点链接到表尾 tail=p; //尾指针指向新结点 } while (e!=0); //不为0 tail->next=NULL; //尾结点的next置为空指针 return head; //返回头指针 }
例2生成“后进先出”单链表(链式栈)。输入:2,8,5,0,生成: head 0 5 8 2∧ 算法: struct Lnode *creat() //生成“后进先出”单链表 I struct Lnode *head, *p head=( struct lnode*) malloc(LENG);/生成表头结点 head->next=NULL //置为空表 do {p=( struct lnode*) malloc(LENG);//生成新结点 scanf(%d3,&(p>data);//输入数,送新结点的data p->next=head->next //新结点插入表头结点之后 head->next=p //尾指针指向新结点 } while(p>data!=0);//不为0 return head //返回头指针
例2 生成“后进先出”单链表(链式栈)。输入:2,8,5,0,生成: head --→ /// --→ 0 --→ 5 --→ 8 --→ 2 ∧ 算法: struct Lnode *creat2( ) //生成“后进先出”单链表 { struct Lnode *head,*p; head=(struct Lnode *)malloc(LENG);//生成表头结点 head->next=NULL; //置为空表 do { p=(struct Lnode *)malloc(LENG);//生成新结点 scanf(“%d”,&(p->data));//输入数,送新结点的data p->next=head->next; //新结点插入表头结点之后 head->next=p; //尾指针指向新结点 } while (p->data!=0); //不为0 return head; //返回头指针 }
初始化: headm输入2: headw2 输入8:head-m 每次输入新元素后: 生成新结点; p=mall(结点大小);p->data=e; ②新结点指针指向首元素;p->next-head->next 新结点作为首元素:head->next=p
初始化:head //// ^ 输入2: head //// 2 ^ p ① ② 每次输入新元素后: • 生成新结点; p=malloc(结点大小); p->data=e; ② 新结点指针指向首元素;p->next=head->next; ③ 新结点作为首元素: head->next=p; head //// 2 ^ ① ② 8 输入8: p ③ ③