版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_41641805/article/details/82973139
//Author:张佳琪
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *next;
}Node,*LinkedList;
LinkedList init()
{
Node *L;
L=(Node *)malloc(sizeof(Node));
if(L==NULL)
printf("fail\n");
L->next=L;
return L;
}
LinkedList create()
{
Node *L;
L=init();
Node *r;
r=L;
ElemType x;
while(scanf("%d",&x))
{
if(x==0)
break;
Node *p;
p=(Node *)malloc(sizeof(Node));
p->data=x;
r->next=p;
r=p;
}
r->next=L;
return L;
}
LinkedList insert(LinkedList L,int i,ElemType x)
{
Node *p;
p=L;
int j;
for(j=1;j<i;j++)
p=p->next;
Node *q;
q=(Node *)malloc(sizeof(Node));
q->data=x;
q->next=p->next;
p->next=q;
return L;
}
LinkedList deleteelem(LinkedList L,ElemType x)
{
Node *p,*q;
p=L;
while(1)
{
if(p->data!=x&&p->next!=L)
{
q=p;
p=p->next;
}
else if(p->data!=x&&p->next==L)
{
break;
}
else if(p->data==x&&p->next!=L)
{
q->next=p->next;
free(p);
p=q->next;
}
else if(p->data==x&&p->next==L)
{
q->next=L;
free(p);
break;
}
}
return L;
}
LinkedList deletepos(LinkedList L,int i)
{
Node *p;
p=L;
int j;
if(i!=1)
{
for(j=1;j<i;j++)
p=p->next;
p->next=p->next->next;
}
else
{
while(p->next!=L)
{
p=p->next;
}
L=p->next->next;
p->next=L;
}
return L;
}
void show(LinkedList L)
{
Node *p;
p=L->next;
while(1)
{
printf("%d ",p->data);
if(p->next==L)
break;
p=p->next;
}
printf("\n");
}
int main()
{
LinkedList L;
int i,j;
while(1)
{
printf("----@@@menu@@@----\n");
printf("1.建立\n");
printf("2.在某位置插入\n");
printf("3.在某位置删除\n");
printf("4.删除特定值\n");
printf("5.输出\n");
printf("输入1-5:");
scanf("%d",&i);
switch(i)
{
case 1:
{
L=create();
break;
}
case 2:
{
printf("在哪里插入,插入啥:");
scanf("%d %d",&i,&j);
L=insert(L,i,j);
break;
}
case 3:
{
printf("删除哪个位置:");
scanf("%d",&i);
L=deletepos(L,i);
break;
}
case 4:
{
printf("删除特定值:");
scanf("%d",&i);
L=deleteelem(L,i);
break;
}
case 5:
{
show(L);
break;
}
}
}