利用顺序栈将带头结点的单链表(a1,a2,…,an)逆置为(an,an-1,…,a1)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include typedefintSElemType;

typedefstruct node

{int data;

struct node *next;

}linklist;

linklist *head;

#define STACK_INIT_SIZE 100

#define STACKINCREMENT 10 typedefstruct {

SElemType *base;

SElemType *top; intstacksize;

} 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");

else

{

do{printf("%6d",p->data); p=p->next;

}while(p!=NULL);

printf("\n");

}

}

intInitStack (SeqStack *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(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 ;

}

intstackempty(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);

}

void main()

{

linklist *head;

head=creatlist();

print(head);

head=backlinklist(head);

print(head);

}

相关文档
最新文档