1逆序输出(10分)
题目内容:
你的程序会读入一系列的正整数,预先不知道正整数的数量,一旦读到-1,就表示输入结束。然后,按照和输入相反的顺序输出所读到的数字,不包括最后标识结束的-1。
输入格式:
一系列正整数,输入-1表示结束,-1不是输入的数据的一部分。
输出格式:
按照与输入相反的顺序输出所有的整数,每个整数后面跟一个空格以与后面的整数区分,最后的整数后面也有空格。
输入样例:
1 2 3 4 -1
输出样例:
4 3 2 1
1、思维有限制,一心想着把数据先倒序保存后,再输出出来。弄的很是麻烦,结果还只得了8分。
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef struct string{
int value;
struct string *next;
}string_1;
int main(int argc, char *argv[]) {
int number;
int cnt=0;
string_1 *head=NULL;
do
{
scanf("%d",&number);
cnt++;
if(number!=-1)
{
string_1 *p=(string_1*)malloc(sizeof(string_1));
p->value=number;
p->next=NULL;
string_1 *last=head;
if(last)
{
while(last->next)
{
last=last->next;
}
last->next=p;
}else{
head=p;
}
}
}while(number!=-1);
cnt--;
int *shu=(int*)malloc(sizeof(string_1)*cnt);//申请了一个内存空间用来存储倒序后的数。
int y=cnt,i=0;
string_1 *put;
cnt--;//数组的最大编号小于数组元素个数1。
for(put=head;put;put=put->next)
{
shu[cnt]=put->value;
// printf("%d\t",put->value);
cnt--;
}
for(i=0;i<y;i++)
{
printf("%d\t",shu[i]);
}
return 0;
}
2、这是看了别人的后,发现可以直接将链表的指针,改成指向前一个指针。
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*只得了8分*/
typedef struct string{
int value;
struct string *next;
}string_1;
int main(int argc, char *argv[]) {
int number;
int cnt=0;
string_1 *last=NULL;
do
{
scanf("%d",&number);
if(number!=-1)
{
string_1 *p=(string_1*)malloc(sizeof(string_1));
p->value=number;
p->next=last;//这就是将指针指向了前一个指针。
last=p;
}
}while(number!=-1);
string_1 *put;
for(put=last;put;put=put->next)
{
printf("%d\t",put->value);
}
return 0;
}