26个字母单链表的插入与删除

//26个字母单链表的插入与删除
#include

#include

typedef struct Sqlist
{
	char data;
	struct Sqlist *next;
}Sqlist, *LinkList;
	Sqlist *p, *q, *head;
	int n;
	int m = sizeof(Sqlist);
	
void bulid()//构建26个字母的单链表 
{
	int i;
	head = (Sqlist*)malloc(m);//分配头结点的空间 
	p = head;
	for (i = 1; i < 26; i++)
	{
		p->data = i + 'a' - 1;
		p->next = (Sqlist*)malloc(m);
		p = p->next;
	}
	p->data = i + 'a' - 1;
	p->next = NULL;
};
void printf()//打印出26字母单链表 
{
	p = head;
	while (p->next != NULL)
	{
		printf("%c", p->data);
		p = p->next;
	}
	printf("%c\n", p->data);
};
void Insert(Sqlist*head)
{
	Sqlist *h;
	p = head;
	int i;
	char s;
	printf("请输入您要插入的位置");
	scanf("%d", &i);
	getchar();
	printf("请输入您要插入的字母");
	scanf("%c", &s);
	printf("\n");
	h = (Sqlist*)malloc(m);//插入新节点 
	h->data = s;
	p = head->next;
	int j=1;
	while (p&&j < i-1)
	{
		q = p;
		p = p->next;
		j++;
	}
	if (!p || j>i)
	{
		h->next = NULL;
		q->next = h;
	}
	else
	{
		h->next = p->next;
		p ->next = h;
	}
	printf();
}
void Delete(Sqlist *head)
{
	p = head;
	int i;
	int j = 1;
	printf("请输入您要删除的位置");
	scanf("%d", &i);
	while (p->next&&j < i - 1)
	{
		p = p->next;
		j++;
	}
	if (!(p->next || j < i - 1))
		printf("出现错误");
	else
	q = p->next;
	p->next = q->next;
	free(q);
}
int main()
{

	bulid();
	printf();
	Insert(head);
	Delete(head);
	printf();
	system("pause");
	return 0;
}
//以下为运行结果:

你可能感兴趣的:(写代码入门,单链表)