问题 E: 算法2-24 单链表反转

题目链接:http://codeup.cn/problem.php?cid=100000607&pid=4

题目描述
根据一个整数序列构造一个单链表,然后将其反转。

例如:原单链表为 2 3 4 5 ,反转之后为5 4 3 2

输入
输入包括多组测试数据,每组测试数据占一行,第一个为大于等于0的整数n,表示该单链表的长度,后面跟着n个整数,表示链表的每一个元素。整数之间用空格隔开

输出
针对每组测试数据,输出包括两行,分别是反转前和反转后的链表元素,用空格隔开

如果链表为空,则只输出一行,list is empty

样例输入
5 1 2 3 4 5
0

样例输出
1 2 3 4 5
5 4 3 2 1
list is empty

代码

#include 
#include 

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

int main() {
	int n, data;
	node* head1, *head2,*r1, *q, *p;
	while(scanf("%d",&n) != EOF) {
		if(n == 0) 
			printf("list is empty\n");
		else {
			head1 = new node;
			head1->next = NULL;
			r1 = head1;
			head2 = new node;
			head2->next = NULL;		
			for(int i = 0; i < n; i++) {
				scanf("%d",&data);
				q = new node;
				q->data = data;
				r1->next = q;
				r1 = q;
				p = new node;
				p->data = data;
				p->next = head2->next;
				head2->next = p;
			}
			r1->next = NULL;
			p = head1->next;
			while(p != NULL) {
				printf("%d ",p->data);
				p = p->next;
			}
			printf("\n");
			p = head2->next;
			while(p != NULL) {
				printf("%d ",p->data);
				p = p->next;
			}
			printf("\n");
		}
	}
	return 0;
}

你可能感兴趣的:(Codeup,算法)