构造C链表

#include<stdio.h>
#include<stdlib.h>

struct node{
    int data;
    struct node *next;
};

int main(){
    int n,a;
    struct node* head = NULL;
    struct node *pre;
    struct node *p;
    scanf("%d",&n);
    for(int i =0;i<n;i++){
        scanf("%d",&a);
        p = (struct node*)malloc(sizeof(struct node)); //申请一块内存
        p->data = a;
        p->next = NULL; //链表无后继指针
        if(head == NULL){    //如果head没有赋值 则这个为第一个元素
            head = p;
        }
        else{
            pre->next = p;//否则上一个元素的后继为这个元素
        }
        pre = p; //这个元素变为上个元素,为下一个输入做准备
    }
    struct node*now = head;//遍历链表
    while(now != NULL){
        printf("%d\n",now->data);
        now = now->next;
    }
    return 0;
}

posted @ 2014-07-30 13:25  心暖向阳。  阅读(196)  评论(0)    收藏  举报