//Author:Pei Chen
//Date:2017.04.30
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node *prior;
struct Node* next;
}Node,*DLinkList;
DLinkList DLinkListCreat()
{
Node *L, *p, *r;
L = (Node *)malloc(sizeof(Node));
L->next = NULL;
L->prior = NULL;
r = L;
r->next = NULL;
r->prior = NULL;
ElemType x;
while ((scanf("%d", &x) != EOF)&&(x!=-1))
{
p = (Node *)malloc(sizeof(Node));
p->data = x;
p->next = r->next;
p->prior = r;
r->next = p;
r = p;
}
r->next = NULL;
return L;
}
int DLinkListFind(DLinkList L, ElemType x)
{
DLinkList p;
p = L->next;
int i = 1;
while (p!=NULL&&p->data!=x)
{
++i;
p = p->next;
}
if (p == NULL)
return 0;
else
{
return i;
}
}
DLinkList DLinkListInsert(DLinkList L, int i, ElemType x)
{
DLinkList p, s,head;
head = L;
p = L->next;
int tempi;
for (tempi = 1; tempi < i - 1; tempi++)
p = p->next;
s = (Node *)malloc(sizeof(Node));
s->data = x;
s->next = p->next;
p->next->prior = s;
s->prior = p;
p->next = s;
return head;
}
DLinkList DLinkListDelete(DLinkList L, int i)
{
int tempi = 1;
DLinkList p,head;
head = L;
printf("iebfeifb00000000000000000\n");
p = L->next;
while ((tempi++)!=i&&p!=NULL)
{
p = p->next;
}
if (p == NULL)
printf("位置不合法。\n");
else if(p->next==NULL)
{
p->prior->next = NULL;
p->prior = NULL;
free(p);
}
else
{
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
}
printf("iebfeifb\n");
return head;
}
void DLinkListPrint(DLinkList L)
{
DLinkList temp;
temp = L->next;
for (; temp != NULL; temp = temp->next)
{
printf("%d ", temp->data);
}
}
int main(int argc, char* argv[])
{
DLinkList list, start;
list = DLinkListCreat();
DLinkListPrint(list);
printf("\n");
int i;
ElemType x;
printf("请输入要查找的元素的值:");
scanf("%d", &x);
i = DLinkListFind(list, x);
if (i)
printf("在链表中的位置为:%d\n", i);
else
{
printf("没有这个元素。\n");
}
printf("请输入插入位置:");
scanf("%d", &i);
printf("请输入插入元素的位置:");
scanf("%d", &x);
list=DLinkListInsert(list, i, x);
DLinkListPrint(list);
printf("\n");
printf("请输入要删除的位置:");
scanf("%d", &i);
list=DLinkListDelete(list, i);
DLinkListPrint(list);
printf("\n");
return 0;
}
一个简单的双端链表实现过程
最新推荐文章于 2019-10-07 17:02:28 发布