游客 Signup | Login
中文 | En

3582 - 线性链表的建立及逆序输出

输入一个正整数序列,遇负数时停止,建立一个线性链表存储读入的数据,将各个元素按逆序输出。

Input

Output

Examples

Input

1 2 3 4 5 -1

Output

5 4 3 2 1

Solution C

#include<stdio.h>
#include<stdlib.h>
typedef struct tagNODE
{
	int number;
	struct tagNODE* next;
}node, * linklist;
void InputAndCreate(linklist* L)
{
	linklist p, s;
	int n;
	p = *L = (linklist)malloc(sizeof(node));
	while (scanf("%d", &n), n >= 0)
	{
		s = (linklist)malloc(sizeof(node));
		s->number = n;
		p->next = s, p = s;
	}
	p->next = NULL;
}
void rOutput(linklist L)
{
	L = L->next;
	if (L->next != NULL)
	{
		rOutput(L);
		printf("%d ", L->number);
	}
	else
	{
		printf("%d ", L->number);
		return;
	}
}
int main()
{
	linklist list;
	InputAndCreate(&list);
	rOutput(list);
	return 0;
}

Solution C++

#include<bits/stdc++.h>
using namespace std;

struct node{
	int data;
	node *next;
};

void Travel(node *head){
	while(head!=NULL){
		cout<<head->data<<" ";
		head = head->next;
	} 
}
int main()
{
	node *p,*h,*head;
	p=NULL;
	int x;
	while(cin>>x&&x!=-1){
		h = new node;
		h->data = x; 
		h->next = p;
		p = h;
	} 
	head = p;
	Travel(head);
	return 0;
}

Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题