1. 程式人生 > >鏈表的遍歷-逆向輸出2-輔助棧

鏈表的遍歷-逆向輸出2-輔助棧

creat 先進後出 typedef bsp node next -s -- malloc

#include<stdio.h>

#include<stdlib.h>

#define N 9

typedef struct node{

int data;

struct node * next;

}ElemSN;

ElemSN * Createlink(int a[],int n){ //逆向創建單向鏈表

int i;

ElemSN * h=NULL, * p;

for( i=N-1;i>=0;i--){

p=(ElemSN *)malloc(sizeof(ElemSN));

p->data =a[i];

p->next=h;

h=p;

}

return h;

}


PrePrintlink(ElemSN*h){

int a[N],top = -1; //輔助棧 先進後出

ElemSN * p;

for(p=h;p;p=p->next){

a[++top] = p->data; //壓棧

}

while(top!=-1){

printf("%5d",a[top--]); //出棧

}

}


int main(void){

int a[N]={1,2,3,4,5,6,7,8,9};

ElemSN * head;

head=Createlink(a,9);

PrePrintlink(head);

}


鏈表的遍歷-逆向輸出2-輔助棧