逆序输出(10分)

版权声明:本文为博主原创文章,未经博主允许不得转载。博客地址: https://blog.csdn.net/qq_40268826/article/details/84779764

逆序输出(10分)

题目内容:

你的程序会读入一系列的正整数,预先不知道正整数的数量,一旦读到-1,就表示输入结束。然后,按照和输入相反的顺序输出所读到的数字,不包括最后标识结束的-1。

输入格式:

一系列正整数,输入-1表示结束,-1不是输入的数据的一部分。

输出格式:

按照与输入相反的顺序输出所有的整数,每个整数后面跟一个空格以与后面的整数区分,最后的整数后面也有空格。

输入样例:

1 2 3 4 -1

输出样例:

4 3 2 1 
//本题单头链表就可以实现,我用的是双头链表
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
	struct node *last;
	int number;
	struct node *next;  //本题可以不用 
} Node;

typedef struct list {
	Node *head;       //本题可以不用 
	Node *last;
}List;

    void add (List *pList, const int num);
    void Put(const List *pList);
    
	int main (void) {
		List list;
		list.head = list.last = NULL;
		int num;
		scanf("%d",&num);
		while (num != -1) {
			add (&list,num);		
			scanf("%d",&num);
		}
		Put(&list);		
		return  0; 
	}

	void add (List *pList, const int num){  
		Node *p =  (Node *) malloc(sizeof(Node));  //分配内存空间 
		p->number = num;
		if (pList->head){     		//*head != null 时输入非第一个节点 
			p->last = pList->last;
			pList->last->next =	pList->last= p;
		}else{		// *head = null  时输入第一个节点 
			p->last = NULL;
			pList->head = pList->last = p;	
		}
			p->next = NULL;
	}
	
    void Put(const List *pList){
    	Node *p = pList->last;
    	for ( ; p ; p=p->last){
    		printf("%d ",p->number);
//   		if (p->last != NULL)
//  			printf(" ");
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_40268826/article/details/84779764