Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
输入
第一行输入整数的个数N;
第二行依次输入每个整数。
第二行依次输入每个整数。
输出
输出这组整数。
示例输入
8 12 56 4 6 55 15 33 62
示例输出
12 56 4 6 55 15 33 62
提示
不得使用数组!
/*
链表创建及遍历
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
// 定义链表中的节点
typedef struct node
{
int data; // 节点中的成员
struct node *next; // 指向下一个节点的指针
}Node,*pNode;
// 函数声明 // 遍历链表函数
// 创建链表函数
pNode CreateList()
{
int i; // 用于下面循环
int len; // 用来存放有效节点的字数
int num; // 用于临时存放用户输入的数据
pNode pHead = (struct node *)malloc(sizeof(struct node)); // 分配一个不存放有效数据的头结点
pNode pTail = pHead; // 链表的最后一个节点
pTail->next = NULL; // 最后一个节点的指针置为空
scanf("%d",&len);
for(i = 0; i < len; i++)
{
scanf("%d",&num);
pNode pNew = (struct node *)malloc(sizeof(struct node)); // 为节点分配空间
pNew->data = num; //将用户输入的数据赋给节点的成员
pTail->next = pNew; //将最后一个节点的指针指向下一个新的节点
pNew->next = NULL; //将新节点中的指针置为空
pTail = pNew; //将新节点赋给最后的一个节点
}
return pHead; //返回头节点
}
// 遍历链表函数
void TraverseList(pNode pHead)
{
pNode p = pHead->next; //将头节点的指针给予临时节点p
while(p!=NULL)
{
//节点p不为空,循环 {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main()
{
pNode Head = NULL; // 定义初始化头节点,等价于 struct Node Head == NULL
Head = CreateList(); // 创建一个非循环单链表,并将该链表的头结点的地址付给pHead
TraverseList(Head); // 调用遍历链表函数
return 0;
}
另一种代码
#include<iostream>
using namespace std;
struct list
{
int i;
list *next;
};
int main()
{
list *head,*p;
int n;
cin>>n;
head=p=new list;
cin>>p->i;
n--;
while(n--)
{
p->next=new list;
p=p->next;
cin>>p->i;
}
p->next=NULL;
for(p=head;; p=p->next)
{
cout<<p->i<<" ";
if(p->next==NULL)
break;
}
return 0;
}