您的位置:首页 > 其它

单向链表的倒序输出(栈实现和递归实现)

2015-09-27 22:38 519 查看
**栈实现**
#include<stdio.h>
#include<malloc.h>
typedef struct node{
int val;
struct node * next;
}NODE,*PNODE;
typedef struct stack{
PNODE head;
PNODE bottom;
}STACK,*PSTACK;
void init(PSTACK s){
s->head=(PNODE)malloc(sizeof(NODE));
if(s->head==NULL)
return;
s->bottom=s->head;
return;
}
void push(PSTACK s,int val){
if(s==NULL)
return;
PNODE newNode=(PNODE)malloc(sizeof(NODE));
newNode->val=val;
newNode->next=s->head;
s->head=newNode;
return;
}
void main(void){
NODE n;
n.val=0;
n.next=NULL;
PNODE phead=&n;
PNODE phead1=phead;
int i;
for(i=1;i<10;i++){
PNODE temp=(PNODE)malloc(sizeof(NODE));
temp->val=i;
phead1->next=temp;
temp->next=NULL;
phead1=temp;
}
STACK s;
init(&s);
PNODE tempNode=phead;
while(tempNode->next!=NULL){
printf("%d ",tempNode->val);
push(&s,tempNode->val);
tempNode=tempNode->next;
}
printf("%d\n",tempNode->val);
push(&s,tempNode->val);
PNODE pTemp=s.head;
while(pTemp!=s.bottom){
printf("%d ",pTemp->val);
pTemp=pTemp->next;
}

}

**递归实现**

#include<stdio.h>
#include<malloc.h>
typedef struct node{
int val;
struct node * next;
}NODE,*PNODE;
void show(PNODE n){
if(n==NULL)
return;
if(n->next!=NULL){
show(n->next);
}
printf("%d",n->val);
}
void main(void){
NODE n;
n.val=-1;
n.next=NULL;
PNODE phead=&n;
int i;
for(i=0;i<10;i++){
PNODE temp=(PNODE)malloc(sizeof(NODE));
temp->val=i;
temp->next=NULL;
phead->next=temp;
phead=temp;
}
show(&n);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息