#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node*link;
};
void push(struct node*,int);
int pop(struct node*);
void delstack(struct node*);
void main()
{ struct node*s = NULL;
int i ;
clrscr();
push(s,14);
push(s,-3);
push(s,18);
push(s,29);
push(s,31);
push(s,16);
i=pop(s);
printf("\n Item popped :%d",i);
i=pop(s);
printf("\n Item popped :%d",i);
i=pop(s);
printf("\n Item popped :%d",i);
delstack(s);
getch();
}
// Add a new node to the stack at the top of the linked list
void push(struct node*top,int item)
{ struct node*temp;
temp=malloc(sizeof(struct node));
if(temp==NULL)
printf("\n Stack is full");
temp->data=item;
temp->link=top;
top=temp;
}
// Pops an element from the stack
int pop(struct node*top)
{ struct node*temp;
int item;
if(top==NULL)
{
printf("\n Stack is empty ");
return NULL;
}
temp=top;
item=temp->data;
top=top->link;
free(temp);
return item;
}
// Deallocates memory
void delstack(struct node*top)
{
struct node*temp;
if(top==NULL)
return;
while(top!=NULL)
{
temp=top;
top=top->link;
free(temp);
}
}
我的問題主要在於指針的使用。這是錯誤的程序,正確的用法是使用雙指針頂部。 但我不明白的是'是否有可能實現它沒有雙指針。如果不是,那麼爲什麼?爲什麼我們需要一個指針指向這裏的指針。實現堆棧作爲鏈表。問題在指針
正確的程序是
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node*link;
};
void push(struct node**,int);
int pop(struct node**);
void delstack(struct node**);
void main()
{ struct node*s = NULL;
int i ;
clrscr();
push(&s,14);
push(&s,-3);
push(&s,18);
push(&s,29);
push(&s,31);
push(&s,16);
i=pop(&s);
printf("\n Item popped :%d",i);
i=pop(&s);
printf("\n Item popped :%d",i);
i=pop(&s);
printf("\n Item popped :%d",i);
delstack(&s);
getch();
}
// Add a new node to the stack at the top of the linked list
void push(struct node**top,int item)
{ struct node*temp;
temp=malloc(sizeof(struct node));
if(temp==NULL)
printf("\n Stack is full");
temp->data=item;
temp->link=*top;
*top=temp;
}
// Pops an element from the stack
int pop(struct node**top)
{ struct node*temp;
int item;
if(*top==NULL)
{
printf("\n Stack is empty ");
return NULL;
}
temp=*top;
item=temp->data;
*top=(*top)->link;
free(temp);
return item;
}
// Deallocates memory
void delstack(struct node**top)
{
struct node*temp;
if(*top==NULL)
return;
while(*top!=NULL)
{
temp=*top;
*top=(*top)->link;
free(temp);
}
}
小建議,工作在你的編碼風格,這意味着,使用更多的空間,不要把東西與塊分隔符同一行。 – 2010-11-27 19:58:27