将单链表中的元素逆序输出,利用栈作为缓冲区


//将单链表中的元素逆序输出,利用栈作为缓冲区

typedef int datatype;

#include

#include

#include

#define NULL 0

#define maxsize 100 /*设栈的最大元素数为100*/

typedef struct node

  datatype data;

  struct node *next;

}linklist;

linklist *head;

/*定义单链表的头指针*/

typedef struct /*定义顺序栈*/

  datatype d[maxsize];

  int top;

}seqstack;

seqstack s1;

/*定义顺序栈的指针*/

linklist *creatlist() /*建立单链表*/

  linklist *p,*q; /*int n=0;*/

  p=q=(struct node *)malloc(sizeof(linklist));

  head=p;

  p->next=NULL; /*头结点的数据域不存放任何东西*/

  p=(struct node *)malloc(sizeof(linklist));

  scanf("%d",&p->data);

  while(p->data!=-1) /*输入-1表示链表结束*/

    q->next=p;

    q=p;

    p=(struct node *)malloc(sizeof(linklist));

    scanf("%d",&p->data);

  q->next=NULL;

  return head;

void print(linklist *head) /*输出单链表*/

  linklist *p;

  p=head->next;

  if (p==NULL)

    printf("This is an empty list.\n");

  else

    do

      printf("%6d",p->data);

      p=p->next;

    }while(p!=NULL);

  printf("\n");

int InitStack(seqstack *s) /*构造一个空栈s*/

  s->top=0;

  return 1;

seqstack *push(seqstack *s,datatype x) /*入栈*/

  if(s->top==maxsize -1)

    printf("栈已满,不能入栈!\n");

    return NULL;

  else

    s->top++; /*栈顶指针上移*/

    s->d[s->top]=x; /*将x存入栈中*/

    return s;

datatype pop(seqstack *s) /*出栈*/

  datatype y;

  if(s->top==0)

    printf("栈为空,无法出栈!\n");

    return 0;

  else

    y=s->d[s->top]; /*栈顶元素出栈,存入y中*/

    s->top--; /*栈顶指针下移*/

    return y;

int StackEmpty(seqstack *s)

  if(s->top==0)

    return 1; /*栈为空时返回1(真)*/

  else

    return 0; /*栈非空时返回0(假)*/

linklist *back_linklist(linklist *head) /*利用栈s逆置单链表*/

  linklist *p;

  InitStack(&s1);

  p=head->next; /*p指向首元结点*/

  /*构造一个空栈,即栈的初始化*/

  while(p)

    push(&s1, p->data); /*链表结点中的数据入栈*/

    p=p->next; /*p指针后移*/

  p=head->next; /*p再指向首元结点*/

  while(!StackEmpty(&s1)) /*当栈S非空时循环*/

    p->data =pop(&s1); /*数据出栈,并存入p所指结点的数据域*/

    p=p->next; /*p指针后移*/

  return head;

///////////主函数//////////

void main()

  linklist *head;

  head=creatlist();

  print(head);

  head= back_linklist(head);

  print(head);