仅实现初始化与插入结点功能
仅作为笔记,记录实现过程中的错误
仅供参考
(初始化后只有一个表头,插入数据的位置要从0开始)
#include<stdio.h>
#include<stdlib.h>
typedef struct List
{
int n;
struct List *next;
} slist; //define the structure of Node
slist* initList(slist *); //init a head
int displayList(slist *); //display the content of the chain table
int insert(slist *); //insert a data in the chain table
int main()
{
slist *head;
int i;
head=initList(head); //creat a null head
printf("init it over,please choose a operation:\n");
printf("1.display\n2.insert\n"); //creat a operation menu
scanf("%d",&i);
while (1) //choose one operation
{
if(i!=1&&i!=2)
{
printf("choose error;\nchoose again:");
scanf("%d",&i);
}
if(i==1)
{
displayList(head);
}
if(i==2)
{
insert(head);
(head->n)++; //the data of head save length of the chain table but not include head itself
}
printf("--operated,please choose again--\n--");
scanf("%d",&i);
}
return 0;
}
slist* initList(slist *p)
{
p=(slist*)malloc(sizeof(slist)); //
p->next=NULL;
p->n=0; //the length of it is 0 firstly
return p; //give head pointer to main
}
int displayList(slist *head)
{
int i=0;
do
{
printf("|--position:%6d --|--data:%6d --\n",i,head->n);
i++;
}
while(head=head->next);
return 0;
}
int insert(slist *head)
{
slist *new;
int c; //data
int n; //position
printf("please give a position(will insert data after this number):");
scanf("%d",&n);
while (n>(head->n)||n<0) //position must not out range
{
printf("\ninvalid position try again\n");
printf("please give a position:");
scanf("%d",&n);
}
printf("input data:");
scanf("%d",&c);
new=(slist*)malloc(sizeof(slist)); //creat new node
while(n--) //pointer get to last node of new node
{
head=head->next;
}
new->next=head->next; //insert chain table
head->next=new;
new->n=c;
return 1;
}
错误:开始把initList函数定义为void类型,刚学,经验不足,对指针理解不够导致。指针本身是一个·储存地址的变量,传入函数后,并不会因函数里面指针储存的地址的变化而变化。而是定义时的地址。我想,可以认为指针本身是一个正常的变量。
总结:想象中很简单的一个东西,实际实现却困难重重,勿好高骛远。