数据结构实验之链表三:链表的逆置
Description
输入多个整数,以-1作为结束标志,顺序建立一个带头结点的单链表,之后对该单链表的数据进行逆置,并输出逆置后的单链表数据。
Input
输入多个整数,以-1作为结束标志。
Output
输出逆置后的单链表数据。
Sample
Input
12 56 4 6 55 15 33 62 -1
Output
62 33 15 55 6 4 56 12
Hint
不得使用数组。
代码:
#include<bits/stdc++.h>
using namespace std;
struct Lnode
{
int data;
struct Lnode *next;
};
void createlist(struct Lnode *l)
{
struct Lnode *h = l;
int a;
while(scanf("%d",&a) && a != -1)
{
struct Lnode *p = new Lnode;
p -> data = a;
p -> next = NULL;
h -> next = p;
h = p;
}
}
int main()
{
struct Lnode *l = new Lnode;
l -> next = NULL;
createlist(l);
struct Lnode *p = new Lnode;
struct Lnode *p2 = l -> next;
l -> next = NULL; // 注意此处要赋NULL,不然会进入死循环
while(p2)
{
p = p2;
p2 = p2->next;
p -> next = NULL;
p -> next = l -> next;
l -> next = p;
}
while(l->next)
{
cout << l->next->data;
l = l -> next;
if(l->next == NULL)
cout << endl;
else
{
cout << " ";
}
}
return 0;
}