之前在创建栈的链式存储结构时,想当然误以为栈的top指针会指向链表的尾结点,在创建链表结构时的写法误写为:
for(j=0;j<i;j++){
temp=(struct Node*)malloc(sizeof(struct Node));
printf("Input:");
scanf("%c",&a);
getchar();
temp->data=a;
temp->next=NULL;
if(!head){
head=tail=temp;
}
else{
tail->next=temp;
tail=temp;
}
}
但创建链表栈是应该是尾结点针为栈底,top指针应该指向头结点,如图:
所以栈的创建、增加、删除结点代码如下所示:
struct Node* create(){
struct Node*temp=0;
temp=(struct Node*)malloc(sizeof(struct Node));
temp->data='a';
temp->next=NULL;
s.top=temp;
s.count=-1;
return temp;
}
bool push(char a,struct linkstack* m){
struct Node* temp=0,*tail=0;
temp=(struct Node*)malloc(sizeof(struct Node));
temp->data=a;
temp->next=m->top;
m->top=temp;
m->count++;
return true;
}
bool pop(struct linkstack* m){
struct Node *p=0;
if(m->count==-1)
return false;
else{
p=m->top;
m->top=m->top->next;
free(p);
m->count--;
return true;
}
}
void read(struct linkstack *s){
struct Node* temp=s->top;
while(temp){
printf("%c",temp->data);
temp=temp->next;
}
}
这样便巧妙地避免了对头结点的记录问题,top就是头结点。