لیست پیوندی در زیان c به زبان ساده
مختصات یک دایره را می گیرد و در لیست قرار می دهد
کد:
#include <stdio.h>
#include <stdlib.h>
struct circle
{
int x , y , r;
circle *link;
}*circlestart;
//----------------------------------------------------------------------------
int circleinsert()
{
circle *ptr;
ptr = (circle*) malloc(sizeof(circle)); //creat a memmory for new item
ptr->link = NULL;
printf("Please Enter x y r seprated by space\n");
int x , y , r;
scanf("%d %d %d" , &x , &y , &r);
ptr->x = x;
ptr->y = y;
ptr->r = r;
if (circlestart == NULL) //if the list is empty put the new one on the first position
{
circlestart = ptr;
return 0;
}
circle *p1;
p1 = circlestart;
while ( p1->link != NULL) //searches for the last item in the list
{
p1 = p1->link;
}
p1->link = ptr;
return 0;
}
//----------------------------------------------------------------------------
int circleshow()
{
if (circlestart == NULL) //if the list is empty
{
printf("No Circle Excist To Show\n");
return 0;
}
circle *ptr;
ptr = circlestart;
while (ptr != NULL) //nevigate all of the list and print it
{
printf("X: %d Y: %d R: %d\n" , ptr->x , ptr->y , ptr->r);
ptr = ptr->link;
}
return 0;
}
//----------------------------------------------------------------------------
int circledelete()
{
if (circlestart == NULL)//if the list is empty
{
printf("No circles to delete\n");
return 0;
}
int x , y ,r;
printf("Please Enter x y r seprate by space to delete\n");
scanf("%d %d %d" , &x , &y , &r);
if (circlestart->x == x && circlestart->y == y && circlestart->r == r) //if the item is in the first position
{
circle *p;
p = circlestart;
circlestart = circlestart->link;
free(p);
printf("deleted\n");
return 0;
}
circle *ptr , *preptr;
ptr = circlestart;
while (ptr->link != NULL) // nevigate all the list to find the item and delete it
{
preptr = ptr;
ptr = ptr->link;
if (ptr->x == x && ptr->y == y && ptr->r == r)
{
(*preptr).link = (*ptr).link;
printf("deleted\n");
free(ptr);
return 0;
}
}
printf("Not Found To Delete\n");
return 0;
}
//----------------------------------------------------------------------------
void menu()
{
printf("Please select an item with entering the number of it\n");
printf("1- Creat a new circle\n");
printf("2- Show circles\n");
printf("3- Delete an exicting circle\n");
printf("4- exit\n");
}
//----------------------------------------------------------------------------
int main()
{
int key;
do
{
menu();
scanf("%d" , &key);
switch(key)
{
case 1:
circleinsert();
break;
case 2:
circleshow();
break;
case 3:
circledelete();
break;
case 4:
return 0;
}
}while(1);
return 0;
}