1.4双向链表表示与实现
1、双向链表是指链表中每个结点都有两个指针域,一个指向后继结点,一个指向前驱结点。prior和next.
2、双向链表也分带头和不带头,带头操作更加方便。双向链表也有循环结构,称双向循环链表。
3、带头双向循环链表的判空条件为head->prior==head或head->next==head;
代码实现:
DLinkList.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node* prior, * next; //p为前指针,q为后指针
}DListNode,*DListLink;
//插入函数
int InsertDList(DListLink head,int i,DataType e)
{
DListNode* p, * s;
int j=0;
p = head->next;
while (p!=head && j<i)
{
p = p->next;
j++;
}
if (j!=i)
{
printf("插入位置不正确");
return 0;
}
s = (DListNode *)malloc(sizeof(DListNode));
if (s==NULL)
{
return -1;
}
s->data = e;
s->prior = p->prior;
p->prior->next = s;
s->next = p;
p->prior = s;
return 1;
}
//删除函数
int DeleteDList(DListLink head, int i, DataType *e)
{
DListNode* p, * s;
int j = 0;
p = head->next;
while (p != head && j < i)
{
p = p->next;
j++;
}
if (j != i)
{
printf("输入位置不正确");
return 0;
}
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
return 1;
}
//初始化函数
int InitDList(DListLink *head)
{
*head = (DListLink)malloc(sizeof(DListNode));
if (!head)
return -1;
(*head)->next = *head;
(*head)->prior = *head;
return 1;
}
//创建循环单链表
int CreateDList(DListLink head,int n)
{
DListNode* s, * q;
DataType e;
q = head;
for (int i = 1; i <= n; i++)
{
printf("请输入第%d个元素:",i);
e = getchar();
s = (DListNode *)malloc(sizeof(DListNode));
s->data = e;
s->next = q->next;
q->next = s;
s->prior = q;
head->prior = s;
q = s;
getchar();
}
return 1;
}
//输出函数
void PrintDList(DListLink head)
{
DListNode* p;
p = head->next;
while (p!=head)
{
printf("%c",p->data);
p = p->next;
}
printf("\n");
}
test.c
#include <stdio.h>
#include <stdlib.h>
#include "DLinkList.h"
void main()
{
DListLink h;
int n;
int pos;
char e;
InitDList(&h);
printf("输入元素的个数:");
scanf_s("%d",&n);
getchar();
CreateDList(h, n);
printf("链表中的元素:");
PrintDList(h);
printf("请输入插入的元素:");
scanf_s("%c",&e);
getchar();
printf("请输入插入元素的位置:");
scanf_s("%d", &pos);
InsertDList(h, pos, e);
printf("插入后链表中的元素:");
PrintDList(h);
}