當前位置:首頁 » 編程語言 » c語言pushpop
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

c語言pushpop

發布時間: 2022-12-27 07:47:24

A. 用c語言實現棧的操作,包括創建空棧,PUSH,和POP。用標准C,就是能在TC上運行的。

#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef char SElemtype;
typedef struct
{
SElemtype *base;
SElemtype *top;
int stacksize;
}SqStack;

int InitStack(SqStack &S);
int Push(SqStack &S, SElemtype e);
int GetTop(SqStack S, SElemtype &e);
int Pop(SqStack &S, SElemtype &e);

int main()
{
SElemtype e, f = 0, g = 0;
int c;

SqStack S;
if (!InitStack(S))
return 0;

printf("棧已初始化好,輸入一個數據入棧.\n");
scanf("%c", &e);
if (!Push(S, e))
return 0;

if (!GetTop(S, f))
return 0;
printf("棧頂元素是:%c\n", f);

if (!Pop(S, g))
return 0;
printf("棧頂元素出棧,它是:%c\n", g);

scanf("%d", &c);
return 1;
}

int InitStack(SqStack &S)
{
S.base = (SElemtype *)malloc(STACK_INIT_SIZE * sizeof (SElemtype));
if (!S.base)
return 0;
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return 1;
}

int Push(SqStack &S, SElemtype e)
{
if (S.top - S.base == S.stacksize)
{
S.base = (SElemtype *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof (SElemtype));
if (!S.base)
return 0;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return 1;
}

int GetTop(SqStack S, SElemtype &e)
{
if (S.top == S.base)
return 0;
e = *(S.top - 1);
return 1;
}

int Pop(SqStack &S, SElemtype &e)
{
if (S.top == S.base)
return 0;
e = *--S.top;
return 1;
}

我學這本書時寫的,剛好給你。

針對補充問題:
&不是偽代碼,是C++的傳引用,你看的那本書上都是這樣用的。
樓上的順序棧實質就是一個數組。。
TC不能建C++項目嗎? 不能的話你還是裝個VC吧,你若聽了老師的話就應該知道在這里傳引用是什麼意思,且看下面:
int InitStack(SqStack &S);
int Push(SqStack &S, SElemtype e);
int GetTop(SqStack S, SElemtype &e);
int Pop(SqStack &S, SElemtype &e);
有沒有發現GetTop()的參數沒有使用&S,因為它對S只讀,不改變S。
如果不使用傳引用的話,那麼InitStack(),Push()等將要返回一個S,若要保存還要把它賦給另一個SqStack類型的變數S1,這樣做浪費時間還浪費空間,且之前的S也就沒用了,如果反復地調用Push()的話,這樣的浪費可想而知。
所以,為了節省時間跟空間,以及按大多數情況下的需要,我們還是得始終只用一個S保存我們要的數據。
至於傳引用是什麼意思,跟指針有點像,你若不想翻書就再補充問題吧。。

B. 「c語言」中,「pop函數」和「push函數」的作用分別是什麼

這個算是數據結構的內容講解的是一個叫做棧類型的數據結構,這個數據結構的特點就是後進先出--最後放進去的數據最先拿出來。pop函數就是拿出數據的操作,push是放入是數據的操作。

C. 怎樣用C語言寫出對棧進行的五種運算:push()、pop()、top()、empty()、makempty()

這是我用鏈表寫的:
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
int x;
struct node *next;
}Node;

typedef struct stack
{
Node *top;
}Stack;

void InitStack(Stack *s)
{
s->top=NULL;
}

int IsEmpty(Stack *s)
{
if(s->top==NULL)
return 1;
else
return 0;
}
void PushStack(Stack *s,int x)
{
Node *p;
p=(Node*)malloc(sizeof(Node));
p->x=x;
// p->next=NULL;

p->next=s->top;
s->top=p;
}

int PopStack(Stack *s)
{
int data;
Node *p;
p=(Node *)malloc(sizeof(Node));
if(IsEmpty(s))
{
printf("the stack is empty!\n");
free(p);
return -1;
}
else
{
p=s->top;
data=p->x;
s->top=p->next;
free(p);
return data;
}
}

int main (int argc,char **argv)
{
int i;
Stack s;
InitStack(&s);
for(i=0;i<1000;i++)
{
PushStack(&s,i);
}
for(i=0;i<1000;i++)
{
printf("%d\n",PopStack(&s));
}
}