c语言 链表存储实现

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<conio.h>  
#define ElemType int
struct LNode{   //定义单链表结点类型 
int data;      //数据域 
struct LNode *next; //指针域 
};       //LinkList相当于LNode*,即:struct LNode*

void creat(struct LNode*head,int size){
struct LNode*p,*new_node;
int i,n;
p=head;//依次读入节点数据
for(i=1;i<=size;i++){
	scanf("%d",&n);
	new_node=(struct LNode*)malloc(sizeof(struct LNode));
	new_node->data=n;
	new_node->next=NULL;
	p->next=new_node;//新节点接入到链表尾 
	p=p->next;//p指针向后移 
} 
}

void print(struct LNode*head){
struct LNode*p;
p=head->next;
while(p!=NULL){
	printf("%d ",p->data);
	p=p->next;
}
}

void ListInsert(struct LNode*head,int i,int e){
struct LNode*p,*new_node;
int k;
new_node=(struct LNode*)malloc(sizeof(struct LNode));//生成新结点 
new_node->data=e;
new_node->next=NULL;
p=head;// 使p指向插入位置的前一个结点 
for(k=2;k<=i&&p->next;k++)
	p=p->next;
	/*插入结点*/ 
if(p->next==NULL) //插入到表尾 
	p->next=new_node;
else{  //插入到p所指向结点之后 
	new_node->next=p->next;
	p->next=new_node; 
} 
}

void ListDelete(struct LNode*head,int i){
struct LNode*p,*q;
int k;
p=head;
for(k=2;k<=i&&p->next;k++)
	p=p->next;
if(p->next){
	q=p->next; //q指向被删除的结点 
	p->next=p->next->next; //把被删除的结点从链表删除 
	free(q); //释放q 
} 
}

int LocateElem(struct LNode*head,char n){
int i=0;
struct LNode*p;
p=head->next;
while(p){
	i++;
	if(p->data==n)
	return i;
}
return -1;
}

int main() 
	{
	struct LNode*head=NULL;
	char e,dele;
	int sel,i,n;
	head=(struct LNode*)malloc(sizeof(struct LNode));
	head->next=NULL;
	sel=-1;
	while(1){
	printf("\n请选择操作");
	printf("\n1.创建:");
	printf("\n2.输出:");
	printf("\n3.插入:");
	printf("\n4.删除: ");
	printf("\n5.查找:");
	printf("\n0.退出:");
	printf("\n请选择你的操作:");
	scanf("%d",&sel);
	if(sel==0)
	break;
		switch(sel)
		{
			case 1:
				printf("请输入要创建链表的元素个数:");
				scanf("%d",&n);
				creat(head,n);
				printf("\n");
				break;
			case 2:
				printf("所有链表元素如下:\n"); 
				print(head);
				printf("\n");
				break;
			case 3:
				printf("请输入要插入的元素");
				scanf("%d",&n);
				printf("请输入要插入的位置");
				scanf("%d",&i);
				ListInsert(head,i,n);
				printf("\n");
				break;
			case 4:
				printf("请输入要删除元素的位置");
				scanf("%d",&i);
				ListDelete(head,i);
				printf("\n");
				break;
			case 5:
				printf("请输入要查找的元素:");
				scanf("%d",&n);
				i=LocateElem(head,n);
				if(n!=-1) { 
				printf("%d是链表的第%d个元素\n",n,i);
				printf("\n");} 
				else{
				printf("查找失败\n");
				printf("\n");}
				break;
			case 0:
				exit(0);
				break; 
		} 
	}
	return 0;
}		

猜你喜欢

转载自blog.csdn.net/weixin_43028756/article/details/83714067