- #include <stdio.h>
- #include <malloc.h>
- #define ElemType int
- typedef struct LNode{
- ElemType data;
- struct LNode *next;
- struct LNode *prior;
- }LNode;
- void InitList(LNode *L)
- {
- L=(LNode*)malloc(sizeof(LNode));
- if(!L)
- printf("创建失败!!\\n");
- L->data=-1;
- L->next=NULL;
- L->prior=NULL;
- }
- void ListInsert(LNode *L,int i,ElemType e)
- {
- int j;
- LNode *s=(LNode*)malloc(sizeof(LNode));
- LNode *p=(LNode*)malloc(sizeof(LNode));
- p=L;
- if (i<1||!L)
- printf("插入位置出错\\n");
- for (j=0;j<i;j++)
- {
- p=p->next;
- }
- s->data=e;
- s->prior=p->prior;p->prior->next=s;
- s->next=p;
- p->prior=s;
- }
- void Create(LNode *L)
- {
- int x;
- LNode *q=(LNode*)malloc(sizeof(LNode));
- q=L;
- printf("请输入要插入的元素:\\n");
- scanf("%d",&x);
- while (x)
- {
- LNode *p=(LNode*)malloc(sizeof(LNode));
- p->data=x;
- p->next=NULL;
- p->prior=q;
- q->next=p;
- q=p;
- scanf("%d",&x);
- }
- }
- void ListDelete(LNode *L,int i)
- {
- int j,e;
- LNode *p=(LNode*)malloc(sizeof(LNode));
- LNode *q=(LNode*)malloc(sizeof(LNode)) ;
- p=L->next;
- for (j=1;j<i;j++)
- {
- p=p->next;
- }
- q=p->next;
- e=q->data;
- p->prior->next=p->next;
- p->next->prior=p->prior;
- }
- void Print(LNode *L)
- {
- LNode *p;
- p=L->next;
- while (p!=NULL)
- {
- printf("%d ",p->data);
- p=p->next;
- }
- printf("\\n");
- }
- int main(void)
- {
- int i,e,di;
- LNode *L=(LNode*)malloc(sizeof(LNode));
- InitList(L);
- printf("请创建一个链表:\\n");
- Create(L);
- Print(L);
- printf("请输入插入位置及元素:\\n");
- scanf("%d%d",&i,&e);
- ListInsert(L,i,e);
- printf("插入后的链表内容为:\\n");
- Print(L);
- printf("请输入删除的位置:\\n");
- scanf("%d",&di);
- ListDelete(L,di);
- printf("删除后的链表变为:\\n");
- Print(L);
- free(L);
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1509201410385.html
来源: http://www.codesnippet.cn/detail/1509201410385.html