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<stdio.h>
#include<stdlib.h>
typedef struct node
{
int num;
struct node* next;
}node;
int n,a[1000];
void shuzu()
{
int i;
for(i = n-1;i>=0;i--)
{
printf("%d ",a[i]);
}
printf("\n");
}
void lianbiao()
{
node *p,*q,*head;
head = (node*)malloc(sizeof(node));
q = head;
for(int i = 0;i < n;i++)
{
p = (node *)malloc(sizeof(node));
p->num = a[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)
{
printf("%d\n",q->num);
break;
}
else
{
printf("%d ",q->num);
q=q->next;
}
}
}
int main()
{
scanf("%d",&n);
for(int i = 0;i < n;i++)
{
scanf("%d",&a[i]);
}
shuzu();
lianbiao();
return 0;
}