Estructura de datos en lenguaje C, realización simple del sistema de sublista lineal


Contenido principal del subsistema de lista lineal : Describe una lista de tipo carácter enlazado individualmente con una estructura; crea una lista lineal; inserta elementos en la lista lineal, elimina elementos y muestra todos los elementos en la lista lineal; diseña un menú de selección con una declaración if.
Código:

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    
    
	char data;
	struct node *next;
}NODE,*PNODE;
PNODE head;
int n;
void create(){
    
    
	char x;
	PNODE p,s;
	int a= 1;
	n = 0;
	head = (PNODE)malloc(sizeof(NODE));
	p = head;
	while(a)
	{
    
    
		printf("请输入一个数,按回车继续,按x结束:");
		scanf("\n%c",&x);
		if(x!='x')
		{
    
    
			s=(PNODE)malloc(sizeof(NODE));
			s->data = x;
			p->next =s;
			s->next= NULL;
			p = s;
		}
		else
			a=0;
	}
}
void insert(int i,char x)
{
    
    
	PNODE p,s;
	int j = 0;
	p = head;
	printf("输入位置和数值\n");
	scanf("%d %c",&i,&x);
	if(i>0)
	{
    
    
		while(p!=NULL && j<i-1)
		{
    
    
			j++;
			p = p->next;
		}
		if(p!=NULL)
		{
    
    
			s = (PNODE)malloc(sizeof(NODE));
			s->data = x;
			s->next = p->next;
			p->next = s;
			n++;
			printf("插入成功\n");
		}
		else
			printf("链表为空或插入位置超界\n");
	}
	else
		printf("插入位置有误");
}
void deletelist(char x)
{
    
    
	PNODE p,q;
	q = head;
	p = head->next;
	printf("请输入你要删除的值");
	scanf("\t\t%c",&x);
	while(p!=NULL && p->data!=x)
	{
    
    
		q = p;
		p = p->next;
	}
	if(p != NULL)
	{
    
    
		q->next = p->next;
		free(p);
		n--;
		printf("删除成功");
	}
	else
		printf("删除失败");
}
void show(){
    
    
	PNODE p;
	p = head;
	printf("显示所有元素:");
	while(p->next!=NULL)
	{
    
    
		printf("%5c",p->next->data);
		p = p->next;
	}
	if(head->next == NULL || p == NULL)
	{
    
    
		printf("链表为空!\n");
	}
}
void main()
{
    
    
	int choose,i,j=1;
	char x;
	head = NULL;
	while(j)
	{
    
    
		printf("\n\t\t------------线性表子系统----------");
		printf("\n\t\t*\t    1----建表\t\t\t*");
		printf("\n\t\t*\t    2----插入\t\t\t*");
		printf("\n\t\t*\t    3----删除\t\t\t*");
		printf("\n\t\t*\t    4----展示\t\t\t*");
		printf("\n\t\t*\t    0----返回\t\t\t*");
		printf("\n\t\t请选择菜单号码\t\t\t*");
		scanf("%d",&choose);
		printf("\n");
		if(choose == 1)
		{
    
    
			create();
			printf("建表成功\n");
		}
		else if(choose == 2)
		{
    
    
			insert(i,x);
		}
		else if(choose == 3)
		{
    
    
			deletelist(x);
		}
	    else if(choose == 4)
		{
    
    
			if(head == NULL)
			printf("线性表为空");
			else
				show();
		}
		else if(choose == 0)
		{
    
    
			j = 0;
		}
		else
			printf("输入错误!\n");
	}
}

Imagen de efecto:

resultado de ejecución

Supongo que te gusta

Origin blog.csdn.net/qq_45728434/article/details/108904135
Recomendado
Clasificación