c 언어 로 단일 체인 표 의 기본 조작 을 실현 합 니 다.
2953 단어 데이터 구조
* * * * 비고: * * * 자신 이 방금 데이터 구 조 를 배 웠 기 때문에 자신의 학습 여정 을 기록 하고 복습 하 는 데 사 용 됩 니 다. 처음에 배 울 때 이해 할 수 없 었 지만 지금 은 어느 정도 이해 가 되 었 습 니 다. 이 코드 에서 각 모듈 의 핵심 조작 을 이해 하고 인쇄 중의 작은 문 제 를 주의해 야 합 니 다.
배 운 책 은 (2 판) 이다.
//
#include
#include
typedef struct node
{
char data; //
struct node *next; //
}node;
void initlist(node *l) //
{
l->next=NULL;
}
void lengthlist(node *l)
{
int length=0;
node *p=l;
while(p!=NULL)
{
p=p->next;
length++;
}
printf(" :%d
",length);
}
void createhead(node *l) //
{
node *p=l,*s;
int flag=1;
char c;
while(flag)
{
if((c=getchar())!='$')
{
s=(node*)malloc(sizeof(node));
s->data=c;
s->next=p->next;
p->next=s;
}
else
{
flag=0;
}
}
}
void createtail(node *l)
{
node *s,*r; // ,
int flag=1;
char c;
r=l;
while(flag)
{
if((c=getchar())!='$')
{
s=(node*)malloc(sizeof(node));
s->data=c;
r->next=s;
r=s;
}
else
{
flag=0;
r->next=NULL;
}
}
}
node *get(node *l,char x) //
{
node *p;
p=l->next;
while(p!=NULL)
{
if(p->data==x)
{
printf("
");
return p;
}
p=p->next;
}
printf("
");
return NULL;
}
node *locate(node *l,int n) //
{
node *p;
int k=0;
p=l->next;
while(p!=NULL&&(knext;
k++;
}
if(k==n)
{
printf(" %d :%c",n,p->data);
return p;
}
else
{
printf("
");
return NULL;
}
}
int insertlist(node *l,int n,char x) //
{
node *p=l->next,*s;
int k=0;
while(p!=NULL&&(knext;
k++;
}
if(p==NULL)
{
printf("
");
return 0;
}
s=(node*)malloc(sizeof(node));
s->data=x;
s->next=p->next;
p->next=s;
return 1;
}
int dellist(node *l,int n) //
{
node *p=l,*r;
int k=0;
while(p!=NULL&&(knext;
k++;
}
if(p==NULL)
{
printf("
");
return 0;
}
r=p->next;
p->next=r->next;
free(r);
return 1;
}
void print(node *l) // , p=l->next ,
{
node *p=l->next;
while(p!=NULL)
{
printf("%c ",p->data);
p=p->next;
}
printf("
");
}
void main()
{
node *s=(node*)malloc(sizeof(node));
initlist(s);
createhead(s); //createtail(s);
print(s);
lengthlist(s);
get(s,'k');
locate(s,5);
insertlist(s,5,'p');
print(s);
insertlist(s,200,'a');
dellist(s,4);
print(s);
dellist(s,300);
}