用C語言建立 線性表## *指針法*

球球同學正在學習數據結構,用指針建立順序表的代碼分享給大家!
包括總代碼,運行結果,和具體分析!如果有錯誤,歡迎大家指正!

總代碼:
#include <stdio.h>
#include <stdlib.h> //malloc函數必須要在stdlib.h頭文件下
typedef int ElemType; //ElemType定義爲int型;
#define List_size 50
typedef struct //重點
{
ElemType elem; //儲存空間基地址
int length; //當前的長度
int listsize; //每次分配到的長度,我的是 50
}Sqlist; //
/
run this program using the console pauser or add your own getch, system(“pause”) or input loop */
void init(Sqlist *p,int k) //初始化
{
int i;
p->elem=(ElemType *)malloc(sizeof(ElemType)*List_size);
if(k)
printf(“Data;”);
for(i=0;i<k;i++)
scanf("%d",&p->elem[i]);
p->length=k;
p->listsize=List_size;
return;
}
void hebing(Sqlist *p,Sqlist *q) //合併兩個表,
{
int i,j,k,x;
for(i=0;ilength;i++)
{
x=q->elem[i];
if(seat(p,x)0)
{
p->elem[p->length++]=x;
}
}
printf(“輸入合併後的序列\n”);
}
int seat(Sqlist p,ElemType x) //進行尋找,表中是否含有這個元素
{
int flag=0,i;
for(i=0;i<p.length;i++)
{
if(x
p.elem[i])
{
flag=1;
break;
}
}
return flag;
}
void showlist(Sqlist p) //展示函數
{
int i;
for(i=0;i<p.length;i++)
printf("%d “,p.elem[i]);
printf(”\n");
}
void quicksort(Sqlist *p,int left,int right)//快速排序
{
int i,j,k,temp;
if(left>right)
{
return;
}
i=left;
j=right;
temp=p->elem[i];
while(i!=j)
{
while(p->elem[j]>=temp&&i<j)
j–;
while(p->elem[i]<=temp&&i<j)
i++;
if(i<j)
{
k=p->elem[i];
p->elem[i]=p->elem[j];
p->elem[j]=k;
}
}
p->elem[left]=p->elem[i];
p->elem[i]=temp;
quicksort(p,left,i-1);
quicksort(p,i+1,right);
return;
}
void insert(Sqlist *p)//插入一個元素
{
int i=0,j;
ElemType e;
printf(“請輸入插入的數:”);
scanf("%d",&e);
while(seat(*p,e)==1)
{
printf(“重複,請重新輸入:”);
scanf("%d",&e);
}
while(p->elem[i]<e)
i++;
p->length++;
for(j=p->length-1;j>i;j–)
p->elem[j]=p->elem[j-1];
p->elem[i]=e;
printf(“加入後的序列:\n”);
quicksort(p,0,p->length-1);
}
void dele(Sqlist *p)//刪除一個元素
{
int i=0,j;
ElemType e;
printf(“請輸入刪除的數:”);
scanf("%d",&e);
while(!seat(*p,e))
{
printf(“沒有這個數!!\n請重新輸入:”);
scanf("%d",&e);
}
while(p->elem[i]!=e)
i++;
j=i;
for(j=i;jlength-2;j++)
p->elem[j]=p->elem[j+1];
p->length–;
printf(“刪除後的序列是:\n”);
}
int main(int argc, char *argv[]) {

Sqlist L1,L2,L3;
init(&L1,4);
init(&L2,4);
hebing(&L1,&L2);
showlist(L1);
quicksort(&L1,0,L1.length-1);
printf(“整理後的序列爲:\n”);
showlist(L1);
insert(&L1);
showlist(L1);
dele(&L1);
showlist(L1);
return 0;
}

運行結果:
在這裏插入圖片描述
主函數:
在這裏插入圖片描述
建立線性表:
在這裏插入圖片描述
接下來是初始化線性表: 注意k是我想要插入的長度,可以改變
在這裏插入圖片描述
接下來是合併兩個線性表: ( 用的是指針,因爲指針代表地址 )把L2合併入L1;
seat()函數的作用是判斷表L1中是否含有那個當前的元素
在這裏插入圖片描述這是展示函數showlist():
在這裏插入圖片描述

接下來對合並後的表進行排序: 這裏我使用的是快速排序(不知道的小夥伴要加油La!)
在這裏插入圖片描述接下來是插入函數:先找到屬於e的位置,然後把後面的元素全部向後移動
在這裏插入圖片描述
最後是刪除函數dele():先找到那個元素,然後把後面的元素竇向前移動一個單位
在這裏插入圖片描述
這就是球球同學的代碼啦,學習之路永無終點,一起努力;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章