⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 list(更新).c

📁 建立一个单链表并对链表进行插入、删除操作 插入运算 在头指针为head的链表中
💻 C
字号:
#include<stdio.h>

struct list{
	char ch;
	struct list *next;
};



struct list *create_list(){
	struct list *head, *tail, *p;
	char ch;
	int size = sizeof(struct list);

    head = tail = NULL;
	printf("input words\n");
	ch=getchar();
	while(ch!='\n'){
		p=(struct list *) malloc(size);
		p->ch=ch;
		if(head==NULL)
			head=p;
		else
			tail->next=p;
		tail=p;
	    ch=getchar();
	}
    tail->next=NULL;
	return head;
}




void print_list(struct list *head)
{
	struct list *ptr;
	for(ptr=head;ptr;ptr=ptr->next)
		putchar(ptr->ch);
	printf("\n");
}





struct list *getnode(char x){
	struct list *s;
	int size=sizeof(struct list);
	s=(struct list *) malloc(size);
	if(s){
		s->ch=x;
	    s->next=NULL;
	}
	return s;
}



struct list *insert_list(struct list *head, char a, char x)
{
	struct list *s, *q;
	s=getnode(x);
	printf("\n");
	if(!s)
		return head;
	if(head==NULL)
	{
		head=s;
		return head;
	}
	if(head->ch==a)
	{
		s->next=head;
		head=s;
		return head;
	}
	q=head;
	while(q->next!=NULL && q->next->ch!=a)
		q=q->next;
	s->next=q->next;
	q->next=s;
	return head;
}

struct list *del_list(struct list *head, char x){
	struct list *p, *q;
	if(head==NULL)
		return NULL;
	if(head->ch==x){
		p=head; 
		head=head->next; 
		free(p);
		return(head);
	}
	q=head;
	while(q->next!=NULL && q->next->ch!=x)
		q=q->next;
	if (q->next!=NULL);
	{
		p=q->next; 
		q->next=p->next; 
		free(p);
	}
	return(head);
}



void main(){
	int choice;
	char a;
	char x;
	struct list *origin;
	struct list *ins;
	struct list *del;
	origin=create_list();
	
	printf("\nselect[1]:insert\n");
	printf("select[2]:delete\n");
	scanf("%d%c", &choice);
	if(choice==1){
		printf("\ninput data and location");
		printf("\nExample:To insert 'a' before 'b',please type 'ab'\n");
		scanf("%c%c",&x,&a);
		ins=insert_list(origin, a, x);
		print_list(ins);
	}
	if(choice==2){
		printf("\ninput data\n");
		scanf("%c",&x);
		del=del_list(origin,x);
		print_list(del);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -