您的位置:首页 > 编程语言 > C语言/C++

C语言单向链表的实现

2017-12-14 17:16 246 查看

1.C语言单向链表的实现

#include<stdio.h>
#include<malloc.h>
//定义链表节点类型,包含数据和指向下一个节点的指针
typedef struct Node
{
int data;
struct Node *next;
}Node,*PNode;

PNode createList(int len);//创建len个节点的链表
void printList(PNode list);//打印输出这个链表

int main()
{
printf("Plz input linkList length:\n");
PNode pTmp=NULL;
int len=0;
scanf("%d",&len);
pTmp=createList(len);
printList(pTmp);
return 0;
}
PNode createList(int len)
{
PNode pHead,pNext,pTail;
int i=0;
pHead=(PNode)malloc(sizeof(Node));
if(pHead==NULL) return 0;
pHead->next=NULL;
pTail=pHead;
for(i=1;i<=len;i++)
{
pNext=(PNode)malloc(sizeof(Node));
printf("Plz input the %d element,s value:",i);
scanf("%d",&(pNext->data));
pNext->next=NULL;
pTail->next=pNext;
pTail=pNext;
}
return pHead;
}
void printList(PNode head)
{
printf("linkList info:\n");
PNode p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n\n");
}

输出:

Plz input linkList length:
8
Plz input the 1 element,s value:1
Plz input the 2 element,s value:2
Plz input the 3 element,s value:3
Plz input the 4 element,s value:4
Plz input the 5 element,s value:5
Plz input the 6 element,s value:6
Plz input the 7 element,s value:7
Plz input the 8 element,s value:8
linkList info:
1 2 3 4 5 6 7 8

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: