0x01.结构
typedef struct SLIST
{
int data;
struct SLIST * next;
struct SLIST* front;
}SLIST;
SLIST* head=NULL;//全局指针
SLIST* end = NULL;
0x02.创建
void CreateList()
{
head = (SLIST*)malloc(sizeof(SLIST));
head->next = head->front = NULL;
end = NULL;
}
0x03.增
void AddData(int m)
{
if (head == NULL)
{
printf("头结点为空,无法插入!!!");
return;
}
SLIST* tmphead = head;
if (tmphead->next == NULL)//当只有一个头结点的时候
{
SLIST* pnew = (SLIST*)malloc(sizeof(SLIST));
pnew->data = m;
pnew->next = tmphead->next;//核心代码
tmphead->next = pnew;
pnew->front = tmphead;
end=pnew;
}
else
{
SLIST* pnew = (SLIST*)malloc(sizeof(SLIST));
pnew->data = m;
/*tmphead->next->front = pnew;//核心代码
pnew->front = tmphead;
pnew->next = tmphead->next;
tmphead->next = pnew;
*/
end->next = pnew;
pnew->front = end;
pnew->next = NULL;
end=end->next;
}
}
0x04.删
void DeleteData(int m)
{
if (head == NULL)
{
printf("链表为空!!!");
return;
}
SLIST* tmphead = head;
while (tmphead->next != NULL)
{
tmphead = tmphead->next;
if (tmphead->data == m)
{
tmphead->front->next = tmphead->next;//核心代码
tmphead->next->front = tmphead->front;//
break;
}
}
free(tmphead);
return;
}
0x05.遍历
void PrintData()
{
if (head == NULL)
{
printf("链表为空!!!");
return;
}
SLIST* tmphead = head;
printf("正向输出结果:\n");
while (tmphead->next != NULL)
{
tmphead = tmphead->next;
printf("%d\n", tmphead->data);
}
//从尾开始遍历
printf("反向输出结果:\n");
while (tmphead->front->front != NULL)
{
printf("%d\n", tmphead->data);
tmphead = tmphead->front;
}
printf("%d\n", tmphead->data);
return;
}
0x06.主函数测试
int main()
{
int n,i,m;
CreateList();
printf("你想为双向链表添加几个元素???");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\n添加第 %d 个元素: 为多少?",i+1);
scanf("%d", &m);
AddData(m);
}
printf("添加完毕!!!\n");
PrintData();
printf("你想删除的元素的值为多少?");
scanf("%d", &m);
DeleteData(m);
PrintData();
}