1、用c语言编写二分查找算法c语言实现下列问题的求解。(1)初始化一个链栈。(2)判断是否?

/*链表实现栈的一系列操作*/
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef struct node
{
int data;
struct node *next;
}LinkStackNode,*LinkStack;
/**********************各个子函数的定义*********************/
void initStack(LinkStack *top);
//初始化链栈
int push(LinkStack top,int n);
//链栈进栈操作
void pop(LinkStack top);
//链栈出栈操作
int getTop(LinkStack top,int *s);
//读取链栈栈顶元素
int main()
{
LinkStack top;
int choice;
while(true)
{
printf("*****************Please enter your choice*****************\n\n");
printf("
choice 1:Stack initialization\n");
printf("
choice 2:Into the stack\n");
printf("
choice 3:Out of the stack\n");
printf("
choice 4:Read the stack elements\n");
printf("
choice 0:exit\n\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
initStack(&top);
break;
case 2:
int n;
printf("Please enter the number into the stack elements:");
scanf("%d",&n);
(push(top,n)==1)?printf("%d个元素依次进栈成功\n",n):printf("%d个元素依次进栈失败\n",n);
break;
case 3:
pop(top);
break;
case 4:
int* s;
(getTop(top,s)==1)? printf("栈顶元素是:%d.\n",*s):printf("An empty stack error!!!!\n"); //三目运算符
break;
case 0:
exit(0);
break;
default:
printf("ERROR!!\n");
exit(0);
break;
}
}
return 0;
}
/**********************各个子函数功能的实现*********************/
void initStack(LinkStack *top)
{
//初始化
*top=(LinkStack)malloc(sizeof(LinkStackNode));
//带头结点的单链表
(*top)->next=NULL;
}
int push(LinkStack top,int n)
//进栈 ,将元素压入栈中
{
LinkStackNode *temp;
int n1,n2;
printf("Please enter into the stack elements in turn:\n");
for(n1=0;n1<n;n1++)
{
scanf("%d",&n2);
temp=(LinkStackNode *)malloc(sizeof(LinkStackNode));
//结点申请空间
if(temp==NULL) return ERROR;
//申请空间失败
temp->data=n2;
temp->next=top->next;
//采用头插法存储元素
top->next=temp;
}
return OK;
}
void pop(LinkStack top)
//栈顶元素出栈
{
int a;
LinkStackNode *temp;
if(top->next==NULL)
{
//栈为空,出栈失败
printf("An empty stack error!!!!\n");
}
else
{
temp=top->next;
a=temp->data;
top->next=temp->next;
free(temp);
printf("栈顶元素%d出栈成功.\n",a);
}
}
int getTop(LinkStack top,int *s)
//获读取栈顶元素
{
if(top->next==NULL)
//栈为空,读取栈顶元素失败
{
return ERROR;
}
else
{
*s=(top->next)->data;
//读取栈顶元素,不出栈
return OK;
}
}转载于:https://www.cnblogs.com/qftm/p/10317154.html}

我要回帖

更多关于 二分查找算法c语言 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信