数据结构02——线性表的就地逆置


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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值