Description
建立逆序链表并输出结果
Input
一组数字 以0结束
Output
链表内容
Sample Input
1 2 3 0
Sample Output
3 2 1
上代码:
//非常简单的链表,注意最后倒序输出时起点是n-1,否则会导致数据溢出
#include<iostream>
using namespace std;
struct list {
int data;
list *next;
};
void createlist(list*& head) {
list* p=NULL;
list* s=NULL;
s = new list;
cin >> s->data;
while (s->data != 0) {
if (head == 0)
head = s;
else
p->next = s;
p = s;
s = new list;
cin >> s->data;
}
p->next = NULL;
delete s;
return;
}
void showlist(list* head,int a[])
{
int n = 0;
while (head) {
a[n] = head->data;
head = head->next;
n++;
}
for (int i = n - 1; i >= 0; i--) {
cout << a[i] << " ";
}
cout << endl;
}
int main() {
list* head = NULL;
int a[100] = {};
createlist(head);
showlist(head, a);
}