c语言实现单链表创建和遍历

#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
    int data;
    struct Node *next;
}Node,*Linklist;
Node *creat_List_a()//尾插法建立单链表
{
    Linklist L;
    Node *p;
    int temp;
    L=(Linklist)malloc(sizeof(Node));
    L->next=NULL;
    scanf("%d",&temp);
    while(temp!=-1)
    {
        p=(Linklist)malloc(sizeof(Node));
        p->data=temp;
        p->next=L->next;
        L->next=p;
        scanf("%d",&temp);
    }
    return L;
}
Node * creat_List_b() //头插法建立单链表
{
    Linklist L;
    int temp;
    Node *p;
    Node *r;
    L=(Linklist)malloc(sizeof(Node));
    L->next=NULL;
    r=L;
    scanf("%d",&temp);
    while(temp!=-1)
    {
        p=(Linklist)malloc(sizeof(Node));
        p->data=temp;
        r->next=p;
        r=p;
        scanf("%d",&temp);
    }
    r->next=NULL;
    return L;
}

int main()
{
    Linklist head;
    int i;
    printf("请输入一个整数,选择创建链表方式:");
    scanf("%d",&i);
    if(i==1)
    {
        head=creat_List_a();
    }

    else
    {
         head=creat_List_b();
    }
    Node *p;
    p=head->next;
    while(p!=NULL)
    {
        printf("%2d",p->data);
        p=p->next;
    }
    return 0;
}

发布了29 篇原创文章 · 获赞 3 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章