终于开始开荒了,数据结构....
先来个顺序表逆置,谁让我菜,先学学别人的代码。
我想弄得就是这样,但是代码有小部分还搞不懂。
先来搞搞基础。
在C中定义一个结构体类型要用typedef:
typedef struct Student
{
int a;
}Stu;
于是在声明变量的时候就可:Stu stu1;(如果没有typedef就必须用struct Student stu1;来声明)
这里的Stu实际上就是struct Student的别名。Stu==struct Stude
另外这里也可以不写Student(于是也不能struct Student stu1;了,必须是Stu stu1;)
typedef struct和struct的区别:
typedef struct tagMyStruct
{
int iNum;
long lLength;
} MyStruct;
上面的tagMyStruct是标识符,MyStruct是变量类型(相当于(int,char等))。
这语句实际上完成两个操作:
1) 定义一个新的结构类型
struct tagMyStruct
{
int iNum;
long lLength;
};
分析:tagMyStruct称为“tag”,即“标签”,实际上是一个临时名字,不论是否有typedefstruct 关键字和tagMyStruct一起,构成了这个结构类型,这个结构都存在。
我们可以用struct tagMyStruct varName来定义变量,但要注意,使用tagMyStruct varName来定义变量是不对的,因为struct 和tagMyStruct合在一起才能表示一个结构类型。
2) typedef为这个新的结构起了一个名字,叫MyStruct。
typedef struct tagMyStruct MyStruct;
因此,MyStruct实际上相当于struct tagMyStruct,我们可以使用MyStruct varName来定义变量。
大概对 typedef和结构体有了个认识。
这个代码总共分为
定义结构体sqlist,打印线性表元素PrintList,创建线性表CreatList,逆置线性表元素ReverseList,主函数main
在这多嘴几句,逆置的过程,简单模拟下
初始 1 2 3 4
i=0
temp=arr.[0]=1;
arr.[0]=l[4-0-1]=1;
arr.[4-0-1]=3;
当前顺序 4 2 3 1
i=1
temp=arr.[1]=2;
arr.[1]=l[4-1-1]=3;
arr.[4-1-1]=2;
当前顺序 4 3 2 1
#include<stdio.h>
#include<stdlib.h>
//https://blog.csdn.net/m_hahahaha1994/article/details/51734658
#define OK 1
#define ERROR -1
#define MAX_SIZE 100
typedef int Status;//用status表示int类型
typedef int ElemType;//定义ElemType为int类型
/**
typedef int width;
typedef int height;
那么用的时候就可以
width x;
height y;
这样比
int x;
int y ;
更容易知道变量的意义
*/
typedef struct sqlist
{
ElemType Elem_array[MAX_SIZE];
int length;
}Sqlist;
void PrintList(Sqlist *L)
{
int i;
for(i = 0;i<L->length;i++)
{
printf("%d\n",L->Elem_array[i]);
}
}
Status CreatList(Sqlist *L)
{
int len;
int i;
//ElemType q;
printf("请输入想要创建表的长度:");
scanf("%d",&len);
if(len<0||len>MAX_SIZE)
return ERROR;
L->length = len;
for(i = 0;i<len;i++)
{
scanf("%d",&L->Elem_array[i]);
}
}
//逆置
Status ReverseList(Sqlist *L)
{
int i;
ElemType temp;
if(L->length==0)
{
printf("表为空!\n");
return ERROR;
}
else
{
for(i = 0;i<L->length/2;i++)
{
temp = L->Elem_array[i];
L->Elem_array[i] = L->Elem_array[L->length-i-1];
L->Elem_array[L->length-i-1]=temp;
}
}
}
void main()
{
Sqlist l;
l.length = 0;
//int l->Elem_array[MAX_SIZE];
//InsertElem(&l,1,2);
//InsertElem(&l,2,2);
//InsertElem(&l,3,2);
CreatList(&l);
printf("线性表的值如下:\n");
PrintList(&l);
ReverseList(&l);
printf("线性表逆置之后的值如下:\n");
PrintList(&l);
}
晚安:if a free society cannot help the many who are poor,it cannot save the few who are rich.