一,靜態順序表
//目的:使用靜態數組完成順序表數據的操作
#include<stdio.h>
int main()
{
int a = 10;
int i = 9;
int insertSite;
int arr[10] = {1,2,3,4,5,6,7};
printf("請輸入插入的位置:");
scanf("%d",&insertSite);
//把10插入到第insertSite位
printf("\n插入后的數組為:");
while(i > insertSite-1)
{
arr[i] = arr[i-1];
i--;
}
arr[insertSite-1] = a;
for(i = 0;i < 10;i++)
{
printf("%4d",arr[i]);
}
return 0;
}
運行結果:
二,動態順序表
//目的:使用動態數組完成順序表數據的操作
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 10;
int i;
int n;
int *p = NULL;
int insertSite;
printf("輸入數組元素的個數:");
scanf("%d",&n);
//申請n個整型內存
p = (int*)malloc(n*sizeof(int));
printf("請輸入元素:");
for(i = 0;i < n;i++)
{
scanf("%d",&p[i]);
}
printf("\n請輸入插入的位置:");
scanf("%d",&insertSite);
//把10插入到第insertSite位
printf("\n插入后的數組為:");
i = n+1;
while(i > insertSite-1)
{
p[i] = p[i-1];
i--;
}
p[insertSite-1] = a;
for(i = 0;i < n+1;i++)
{
printf("%4d",p[i]);
}
free(p);
return 0;
}
運行結果:
三,鏈錶原理
//目的:單向鏈錶的數據的操作
//目的:單向鏈錶的數據的操作
#include<stdio.h>
#include<stdlib.h>
struct link
{
int data;
struct link *next;
};
int main()
{
int i = 3,j = 1;
struct link *p = NULL;//第一個節點
struct link *pr= NULL;//第二個節點
struct link *pt= NULL;//第三個節點
//第一個節點的指針指向malloc開闢的一塊大小為struct link類型的內存空間
//在此內存空間裏面的指針指向第二個節點
//再由第二個節點指向malloc開闢的一片struct link 的內存空間
//如此往復
p = (struct link*)malloc(sizeof(struct link));
printf("請輸入數據:");
scanf("%d",&(p -> data));
pr = (struct link*)malloc(sizeof(struct link));
printf("請輸入數據:");
scanf("%d",&(pr -> data));
pt = (struct link*)malloc(sizeof(struct link));
printf("請輸入數據:");
scanf("%d",&(pt -> data));
p -> next = pr;
pr -> next = pt;
pt -> next = NULL;
while(i > 0)
{
printf("\n輸出第%d個數據:%d",j,p -> data);
p = p -> next;
j++;
i--;
}
return 0;
}
運行結果:
四,單向鏈錶
//單向鏈錶
#include<stdio.h>
#include<stdlib.h>
struct link *addnote();
int out(int i,struct link *head);
struct link
{
int data;
struct link *next;
};
int main()
{
int i,j = 0;
struct link *head = NULL;
printf("請問要建立幾個結點:");
scanf("%d",&i);
printf("\n");
while(i > 0)
{
head = addnote(head);
i--;
j++;
}
out(j,head);
}
struct link *(addnote(struct link *head))
{
int data;
struct link *p =NULL,*pr = head;
p = (struct link*)malloc(sizeof(struct link));
if(head == NULL)
{
head = p;
}
else
{
while(pr -> next != NULL)
{
pr = pr -> next;
}
pr -> next = p;
}
printf("請輸入數據:");
scanf("%d",&data);
p -> data = data;
p -> next = NULL;
return head;
}
int out(int i,struct link *head)
{
int j = 1;
struct link *p = head;
printf("\n");
while(i > 0)
{
printf("第%d個數據為%d\n",j,p -> data);
p = p -> next;
i--;
j++;
}
return 0;
}
運行結果: