之前也学过链表,但是没有好好的系统的从头开始学,所以这次暑假打算从头开始刷一下链表的题目,有需要的可以跟着我一起从头开始练习链表的题目,然后这道题目是最基础的,需要注意的地方就是最后输出我用了printf而不是cout是因为如果用cout会时间超限
输入
输入一些整数,均为大于0的数,直到输入一个负数为止。
要求把所有的正整数,建立一个单向链表。
输出
按照顺序输出链表的值
样例输入 Copy
1 2 3 4 5 6 -1
样例输出 Copy
1 2 3 4 5 6
#include<iostream>
#include<malloc.h>
struct node
{
int num;
struct node* next;//一个指向node结构体的next指针,struct node表示类型,*next表示指针
};
using namespace std;
int main()
{
struct node* head,*tail,*p;
int num;
head = tail =NULL;
cin >> num;
while (num > 0)
{
p = (node *)malloc(sizeof(node));
p->num = num;
p->next = NULL;
if (head==NULL)//当没有节点时,应该把head指向头节点
{
head= p;
}
else
{
tail->next = p;
}
tail = p;
cin >> num;
}
for (p = head; p != NULL; p = p->next)
{
printf("%d\n", p->num);
}
return 0;
}