引言
可变参函数有比较重要意义,例如我们常用的printf()函数就使用了这一技术,当然我们这次
用的技术不是实现printf()所用到的。可变参函数其实可以借用
链式栈实现,我们将要传的参数
放到栈中,把栈作为参数进行传递,利用栈先进后出的特点,
可以用链式栈实现
较为简单的
可变参函数。
代码如下:
//本程序用链式栈实现可变参函数编程
//为了方便在main函数传递参数,规定eletype中:1代表int ,2代表char
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct StackLink
{
int eletype;
void *elevalue;
struct StackLink * next;
}StackLink;
//全局变量POPELE
StackLink *POPELE;
//以下是函数声明
StackLink *createStackLink(int eletype , void *elevalue );
void pushStackLink(StackLink *head , int eletype , void *elevalue);
StackLink *popStackLink(StackLink *head);
void printfStackLink(StackLink *head);
StackLink *GetStackLinkTail(StackLink *head , int flag);
int main()//主要用于测试
{
int x = 43;
int HeadEleValue = 13;
int haha = 11;
char xixi[] = "xixi";
char hehe[] = "hehe";
StackLink *head = NULL;
head = createStackLink(1,(void*)(&HeadEleValue));
printfStackLink(head);
pushStackLink(head , 1, (void*)(&haha));
printfStackLink(head);
pushStackLink(head , 2 ,(void*)xixi);
pushStackLink(head , 1 ,(void*)&x);
pushStackLink(head , 2 ,(void*)hehe);
printfStackLink(head);
popStackLink(head);
popStackLink(head);
popStackLink(head);
popStackLink(head);
popStackLink(head);
printfStackLink(head);
free(head);
}
StackLink *createStackLink(int eletype ,void *elevalue)
{
StackLink *head = (StackLink *)malloc(sizeof(StackLink));
head ->eletype = eletype;
head ->elevalue = elevalue;
head ->next =NULL;
return head;
}
void pushStackLink(StackLink *head , int eletype , void *elevalue)
{
StackLink *tail = GetStackLinkTail(head , 1);
StackLink *tmp = (StackLink *)malloc(sizeof(StackLink));
tmp ->eletype = eletype;
tmp ->elevalue = elevalue;
tmp ->next =NULL;
tail ->next= tmp;
}
StackLink *GetStackLinkTail(StackLink *head , int flag)
{
StackLink *tail = head;
if(flag == 1)
{
while(tail ->next !=NULL)
tail = tail ->next;
}
else if(flag == 2)
{
while(tail ->next ->next != NULL)
tail = tail ->next;
}
else
{
printf("flag输入错误\n");
exit(1);
}
return tail;
}
void printfStackLink(StackLink *head)
{
printf("栈中的元素如下:\n");
while(head != NULL)
{
if(head ->eletype == 1)
{
printf("类型为int\t");
printf("%d\n",*(int *)head ->elevalue);
}
else if(head ->eletype == 2)
{
printf("类型为char\t");
printf("%s\n" , (char *)head ->elevalue);
}
else
{
printf("输入有误");
exit(1);
}
head = head ->next;
}
printf("\n\n");
}
StackLink *popStackLink(StackLink *head)
{//将head修改,取出栈顶元素
StackLink *newtail;
if(head ->next == NULL)
{
printf("只剩一个元素,不能弹出\n");
exit(1);
}
newtail = GetStackLinkTail(head , 2);
POPELE = newtail ->next;
printf("弹出的元素如下\n");
if(POPELE ->eletype == 1)
printf("类型是int , 值是%d\n",*(int *)POPELE ->elevalue);
else if(POPELE ->eletype == 2)
printf("类型是char ,值是%s\n",(char*)POPELE ->elevalue);
else
{
printf("eletype有误\n");
exit(1);
}
newtail ->next = NULL;
printf("\n\n");
return newtail;
}