链表笔记1
2019-03-04 本文已影响5人
cjs2019
直接上代码
老师讲课的时候顺便写的,好像是没有传值调用的那种。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define STOP_SIGNAL -1
struct node{//单向链表;
int data;
node* nextPtr;
};
typedef node LISTNODE;
void create_one_node(node** headPtr,node** ptr,node** lastPtr,int* cnt,int num){
//还是喜欢传引用~~
if ((*headPtr)==NULL){
(*ptr)=(node*)malloc(sizeof(node));
if ((*ptr)==NULL){
printf("malloc error!\n");
}
else{
(*headPtr)=(*ptr);
(*cnt)++;
(*lastPtr)=(*ptr);
(*ptr)->data=num;
}
}
else{
(*ptr)=(node*)malloc(sizeof(node));
if ((*ptr)==NULL){
printf("malloc error!\n");
}
else{
(*lastPtr)->nextPtr=(*ptr);
(*ptr)->data=num;
(*lastPtr)=(*ptr);
(*cnt)++;
}
}
}
void examine_result_of_creating_a_list_1(node* headPtr,int cnt){
if (headPtr==NULL){
printf("It is an empty list!\n");
}
else{
node* ptr;
ptr=headPtr;
for (int i = 0; i < cnt; ++i) {
printf("%d ",ptr->data);
ptr=ptr->nextPtr;
}
}
}
//法2:
void examine_result_of_creating_a_list_2(node* headPtr){
if (headPtr==NULL){
printf("It is an empty list!\n");
}
else{
node* ptr;
ptr=headPtr;
while (ptr!=NULL){
printf("%d ",ptr->data);
}
ptr=ptr->nextPtr;
}
}
int main(){
node *headPtr=NULL,*ptr=NULL,*lastPtr=NULL;
int num,cnt=0;
scanf("%d",&num);
while (num!=STOP_SIGNAL){
create_one_node(&headPtr,&ptr,&lastPtr,&cnt,num);
scanf("%d",&num);
}
examine_result_of_creating_a_list_1(headPtr,cnt);
return 0;
}