69,371
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int SElemType;
typedef struct node
{
int data;
struct node *next;
}linklist;
linklist *head;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
} SeqStack;
SeqStack *S;
linklist *creatlist()
{
linklist *p,*q;
int n=0;
q = p = (struct node *)malloc(sizeof(linklist));
head = p;
p->next = NULL;
p = (struct node *)malloc(sizeof(linklist));
scanf("%d", &p->data);
while(p->data!=-1)
{
n = n+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");
return;
}
do {
printf("%6d",p->data);
p = p->next;
}while(p);
printf("\n");
}
int InitStack(SeqStack **S )
{
*S = (SeqStack *)malloc(sizeof(SeqStack));
if (!(*S))
return 0;
(*S)->base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if ((*S)->base == NULL)
return 0;
(*S)->top = (*S)->base;
(*S)->stacksize = STACK_INIT_SIZE;
return 1;
}
int push(SeqStack *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 Pop (SeqStack *S )
{
if(S->top == S->base)
return 0;
S->top--;
return *S->top ;
}
int stackempty(SeqStack *S)
{
if (S->top == S->base)
return 1;
else return 0;
}
linklist *backlinklist(linklist *head)
{
linklist *p;
p = head->next;
InitStack (&S);
while(p)
{
if( push(S, p->data));
p = p->next;
}
p = head->next;
while(!stackempty(S))
{
p->data = Pop(S);
p = p->next;
}
return(head);
}
int main()
{
linklist *head;
head=creatlist();
print(head);
head = backlinklist(head);
print(head);
return 0;
}