Description
试分别以不同的存储结构实现线性表的就地逆置算法,即在原表的存储空间将线性表(a1,a2,…,an)逆置为(an,an-1,…,a1)。
以一维数组作存储结构。
以单链表作存储结构。
Input
第一行输入线性表元素个数elenum;(0<elenum<1000)
第二行输入elenum个数,作为线性表中的元素(a1,a2,…,an)。
Output
分两行分别输出要求(1)和要求(2)的线性表逆置结果(an,an-1,…,a1)。
-
Sample Input
5 2 5 3 7 15
-
Sample Output
15 7 3 5 2 15 7 3 5 2
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct node{
int num;
node* next;
}node;
int n;
int ray[1005];
void array(){
int i;
cout<<ray[n-1];
for(i=n-2;i>=0;i--){
cout<<" "<<ray[i];
}
cout<<endl;
}
void list(){
node *head,*p,*q;
int i;
head=(node*)malloc(sizeof(node)); /*创建头节点*/
/*赋值*/
q=head;
for(i=0;i<n;i++){
p=(node*)malloc(sizeof(node));
p->num=ray[i];
q->next=p;
q=p;
}
q->next=NULL;
/*头插法*/
p=head->next;
head->next=NULL;
while(p){
q=p;
p=p->next;
q->next=head->next;
head->next=q;
}
q=head->next;
while(1){
if(q->next==NULL){
cout<<q->num<<endl;
break;
}
else{
cout<<q->num<<" ";
q=q->next;
}
}
}
int main(){
int i;
cin>>n;
for(i=0;i<n;i++){
cin>>ray[i];
}
array();
list();
return 0;
}
复习:
#include<stdio.h>
#include<stdlib.h>
#define Max 100
typedef struct SeqList{
int array[Max];
int num;
}SeqList;
typedef struct LinList{
int data;
int length;
struct LinList *next;
}LinList;
void init(SeqList *p, LinList *q){
int i, m, x;
scanf("%d", &m);
p->num = m;
q->length = m;
LinList *g;
for(i = 0; i < m; i++){
scanf("%d", &x);
p->array[i] = x;
g = (LinList*)malloc(sizeof(LinList));
g->data = x;
q->next = g;
q = g;
}
q->next = NULL;
}
void invLLink(LinList *q){
LinList *g, *t;
g = q->next;
q->next = NULL;
while(g){
t = g;
g = g->next;
t->next = q->next;
q->next = t;
}
}
void outputS(SeqList *p){
int i;
for(i = p->num-1; i >= 0; i--){
printf("%d ", p->array[i]);
}
printf("\n");
}
void outputL(LinList *q){
LinList *g;
g = q->next;
while(g){
printf("%d ", g->data);
g = g->next;
}
printf("\n");
}
int main(){
SeqList *p = (SeqList*)malloc(sizeof(SeqList));
LinList *q = (LinList*)malloc(sizeof(LinList));
init(p,q);
invLLink(q);
outputS(p);
outputL(q);
return 0;
}