#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node *next;
};
//建立n个数据节点的链表
struct node *createlist(int n)
{
int i;
struct node *head,*p,*q;
p=(struct node *)malloc(sizeof(struct node));
head=q=p;
for(i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data); //从键盘输入一个整数到p->data
q->next=p; q=p;
}
q->next=NULL; //p->next=NULL;
return head;
}
//输出链表内容函数
void printlist(struct node *head)
{
//判断链表是否为空
//p指向第一个数据节点
/*while (exp) //exp表示节点是否存在
{
//输出该节点数据;p=p->next; NULL:0
}
*/
struct node *p;
p=head;
if (p!=NULL)
{
p=p->next;
while (p->next!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
//单独处理一下最后一个节点
printf("%d",p->data);
}
}
int main()
{
struct node *head=NULL;
int n;
scanf("%d",&n);
head=createlist(n);
printlist(head);
return 0;
}
拓展1:能否将最后一个数据后面的->去掉
方法:优先处理前边的数据,把最后一个数据单独处理
上一页
[1]
[2]