1. 程式人生 > 其它 >演算法之旅 | 選擇排序法

演算法之旅 | 選擇排序法

//該程式完成“動態記憶體分配”

#include <stdio.h>
#include <stdlib.h>

typedef struct node //結構體,有兩個分量,一個是資料,另一個是指標
{
int data;
struct node *next;
}linklist;

//主選單
int menu()
{
printf("\n**********************************\n");
printf("1. 建立單鏈表\n");
printf("2. 向單鏈表中插入一個元素\n");
printf("3. 定位單鏈表中的某個元素\n");
printf("0. 退出系統\n");
printf("\n**********************************\n");
}

//退出選單
int menu_bye()
{
printf("\n**********************************\n");
printf("\n 歡迎再次使用\n");
printf("\n 再見\n");
printf("\n**********************************\n");
}

//建立單鏈表
linklist *creat()
{
linklist *head,*p,*q;
head=(linklist *)malloc(sizeof(struct node));
head->next=NULL;
p=q=(linklist *)malloc(sizeof(struct node));
head->next=p;
p->next=NULL;
scanf("%d",&(p->data));
while(p->data!=-1)
{
q->next=p;
q=p;
p=(linklist *)malloc(sizeof(struct node));
scanf("%d",&(p->data));
}
q->next=NULL;
return head;
}

//向單鏈表中插入一個結點
int insertlinklist(linklist *head,int x,int i)
{
linklist *p,*q=head;
if(i==1)
q=head;
else
{
q=q->next;
int c=1;
while(c<i-1 && q!=NULL)
{
q=q->next;
c++;
}
}
if(q!=NULL && q->next!=NULL)
{
p=(linklist *)malloc(sizeof(struct node));
p->data=x;
p->next=q->next;
q->next=p;
}
else
printf("\n找不到要插入結點的位置\n");
}

//定位某個元素的位置
int locatelinklist(linklist *head,int x)
{
linklist *p;
int loc=0;
p=head;
while(p!=NULL && p->data!=x)
{
loc++;
p=p->next;
}
if(p!=NULL)
return loc;
else
return 0;
}

//顯示單鏈表
int print(linklist *head)
{
linklist *p;
p=head->next;
if(p==NULL)
{
printf("空連結串列!");
}
do
{
printf("%4d",p->data);
p=p->next;
}while(p!=NULL);

printf("\n");
}

linklist *h;

//主函式
int main()
{
menu();
int n;
while(1)
{
printf("請輸入(0-7):");
scanf("%d",&n);
if(n<0 || n>7)
printf("沒有此值,請重新輸入!\n");
switch(n)
{
case 0:
system("cls");
menu_bye();
exit(0);
case 1:
printf("請輸入一串整數,以空格分隔,以-1結束.\n");
h=creat();
print(h);
break;
case 2:
int number,pos;
printf("\n輸入要插入結點的值和位置:\n");
scanf("%d%d",&number,&pos);
insertlinklist(h,number,pos); //函式呼叫
print(h);
break;
case 3:
int data,position;
printf("\n請輸入要定位的值:");
scanf("%d",&data);
position=locatelinklist(h,data);
printf("位置是: %d",position);
printf("\n");
break;
}
}

}

 

 

效果圖