数据结构实验之链表二:逆序建立链表

来源:互联网 发布:linux发送邮件超时 编辑:程序博客网 时间:2024/05/16 18:51


这道题的算法思想是从头部插入的方法建立链表。

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct node{/*链表的定义*/
    int data;
    struct node* next;
};
struct node* Creatlist(int n){/*创建链表,从头部插入*/
    struct node* head,*p;/*定义结构体变量*/
    int i,d;
    head=(struct node*)malloc(sizeof(struct node));/*为头指针申请内存空间*/
    head->next=NULL;
    for (i=1;i<=n;i++){
        p=(struct node*)malloc(sizeof(struct node));
        scanf("%d",&d);
        p->data=d;
        p->next=head->next;
        head->next=p;
    }
    return head;
};
void Putlist(struct node* head){/*输出函数*/
    struct node* p;
    p=head->next;
    while (p){
        if (p==head->next)
            printf("%d",p->data);
        else
            printf(" %d",p->data);
        p=p->next;/*指向下一个节点*/
    }
}
int main(){
    int i,j,n;
    struct node* head;
    scanf("%d",&n);
    head=Creatlist(n);
    Putlist(head);
    return 0;
}

0 0