数据结构实验之链表三:链表的逆置
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
输入多个整数,以-1作为结束标志,顺序建立一个带头结点的单链表,之后对该单链表的数据进行逆置,并输出逆置后的单链表数据。
Input
输入多个整数,以-1作为结束标志。
Output
输出逆置后的单链表数据。
Example Input
12 56 4 6 55 15 33 62 -1
Example Output
62 33 15 55 6 4 56 12
Hint
不得使用数组。
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
int date;
struct node *next;
}Lnode;
Lnode *creat(int x)//建表 输入
{
Lnode *p,*q,*head;
int k;
//head = (Lnode*)malloc(sizeof(Lnode));
head = new node;
head -> next = NULL;
q = head;
p = new node;
p -> next = NULL;
p->date = x;
q ->next = p;
q = p;
while(cin >> k && k != -1 )
{
p = new node;
p -> next = NULL;
p->date = k;
q ->next = p;
q = p;
}
return head;
}
void output( Lnode *head)
{
Lnode *q;
q = head ->next;
cout << q ->date;
while(q->next)
{
cout << " " << q ->next ->date;
q = q ->next;
}
cout << endl;
}
Lnode *change(Lnode * head)//元素逆置
{
Lnode *p, *q, *L;
L = new node;
L -> next = NULL;
q = L;
while(head->next)
{
p = new node;
p -> next = NULL;
p ->date = head ->next ->date;
p ->next = q ->next;
q ->next = p;
head = head ->next;
}
return L;
}
int main()
{
int x;
Lnode *head;
cin >> x;
head = creat(x);
head = change(head);
output(head);
return 0;
}