顺序表的逆置
#include<iostream>
#include<string.h>
#include<stdlib.h>
#define ElemType int
#define MaxSize 100
using namespace std;
typedef struct{
ElemType data[MaxSize];
int length;
}SqList; //定义结构类型
//初始化顺序表函数
void IniteList(SqList &L){
memset(L.data,0,sizeof(L));
L.length = 0;
}
//创建顺序表函数
bool CreateList(SqList &L,int n){
if(n<1||n>MaxSize)
return false;
L.length=n;
cout << "请输入创建顺序表中的元素并用空格隔开:";
for(int i=0;i<L.length;i++){
cin >> L.data[i];
}
return true;
}
//逆置操作函数
void Inversion(SqList &L){
int t; //t适用于交换的中间变量
for(int i=0;i<L.length/2;i++){
t = L.data[i];
L.data[i] = L.data[L.length-1-i];
L.data[L.length-1-i] = t;
}
}
//打印出顺序表中所有元素
void PrinteList(SqList &L){
cout << "当前顺序表中元素为:";
for(int j=0;j<L.length;j++)
cout << L.data[j] << " ";
cout << endl;
}
//创建
void Create(SqList &L){
int n;bool flag;
cout << "请输入创建顺序表元素的个数:";
cin >> n;
flag = CreateList(L,n);
if(flag){
cout << "创建成功!\n";
PrinteList(L);
}
else
cout << "创建失败!\n";
}
int main(){
SqList L;
IniteList(L);
Create(L);
Inversion(L);
cout << "逆置操作后";
PrinteList(L);
return 0;
}
带头节点的单链表的逆置
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node{
int data;
Node *next;
}*Linklist;
Linklist creat(Linklist L){
Node *p,*r;
int x;
L=(Linklist)malloc(sizeof(Node));
/*L=new Node;*/
L->next=0;
r=L;
cin>>x;
while(x!=-1){
p=(Linklist)malloc(sizeof(Node));
/*p=new Node;*/
p->data=x;
p->next=0;
r->next=p;
r=p;
cin>>x;
}
return L;
}
void reverse(Linklist L){
Node *p,*q;
p=L->next;
L->next=0;
while(p!=0){
q=p->next;
p->next=L->next;
L->next=p;
p=q;
}
return ;
}
void show(Linklist L){
Node *p;
p=L->next;
while(p!=0){
cout<<p->data<<' ';
p=p->next;
}
return ;
}
int main(){
Linklist La;
La=creat(La);
reverse(La);
show(La);
}