c语言实现单向链表

#include"stdio.h"
#include"stdlib.h"  
#include"malloc.h"
typedef struct node{
   int data;
   struct node *next;
}Node,*pNode;

//生成单项链表,尾部插入
pNode creat(){
    int val,i,m;
    pNode head=(pNode)malloc(sizeof(Node));//为head分配内存
    pNode ptail=head;
    ptail->next=NULL;
    pNode pNew;
    printf("输入节点数:");
    scanf("%d",&m);
    for(i=0;i<m;i++)
    {
        pNew=(pNode)malloc(sizeof(Node));
        printf("输入节点值:");
        scanf("%d",&val);
        pNew->data=val;
        ptail->next=pNew;
        pNew->next=NULL;
        ptail=pNew;
    }
    return head;
}
//遍历单项链表
void traver(pNode head)
{
   pNode p=head->next;
   while(p!=NULL)
    {
       printf("%d",p->data);
       p=p->next;
    }

}

//主函数
int main()
{
   pNode head;
   head=creat();
   traver(head);
   return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38483191/article/details/80261557