#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
//双向链表
typedef int Elemtype;
typedef struct DNode
{
Elemtype data;
struct DNode *prior,*next;
} DNode,*DLinkList;
//尾插法创建链表
DLinkList CreateList()
{
int x;
DLinkList head=(DLinkList)malloc(sizeof(DLinkList));//创建双向链表,头节点
DNode* p=head,*s;//p为遍历节点,s为当前节点
p->prior=NULL;
printf("创建链表,输入9999表示结束\n");
scanf("%d",&x);
while(x!=9999)
{
s=(DNode*)malloc(sizeof(DNode*));
s->data=x;
s->prior=p;
p->next=s;
p=s;
scanf("%d",&x);
}
s->next=NULL;//不要忘记制空尾指针
return head;//返回头节点
}
//遍历链表
void PrintList(DLinkList L)
{
DNode *p;
p=L->next;//找到头节点下一个节点
printf("链表元素如下:\n");
while(p)
{
printf("%d<---->",p->data);
p=p->next;
}
printf("\n");
}
//双链表头插法
DLinkList InsertListHead(DLinkList L,Elemtype e)
{
DNode *p=(DNode*)malloc(sizeof(DNode*));
p->data=e;
p->prior==L;
p->next=L->next;
if(p->next!=NULL)
{
L->next->prior=p;
}
L->next=p;
return L;
}
//队尾插入
DLinkList InsertListTail(DLinkList L,Elemtype e)
{
DNode *s=(DNode*)malloc(sizeof(DNode*));//s为待插入节点
DNode *p=L->next;//p为遍历节点
while(p->next)
{
p=p->next;
}
p->next=s;
s->data=e;
s->prior=p;
s->next=NULL;
return L;
}
//获取链表长度
int GetLength(DLinkList L)
{
int len=0;
DNode *r=(DNode*)malloc(sizeof(DNode*));
r=L->next;
while(r)
{
r=r->next;
len++;
}
return len;
}
//在指定位置插入节点
bool InsertPosition(DLinkList L,int pos,Elemtype e)
{
if(pos<1||pos>GetLength(L)+1)return false;
DNode *r,*n;//r遍历节点
n=(DNode*)malloc(sizeof(DNode*));//插入节点
n->data=e;
n->next=NULL;
r=L;
while(--pos>0)
{
r=r->next;
}
if(r->next==NULL) //在结尾插入
{
r->next=n;
n->prior=r;
return true;
}
n->next=r->next;
r->next->prior=n;
r->next=n;
n->prior=r;
return true;
}
//删除指定节点元素
bool DeletePosition(DLinkList L,int pos,Elemtype *e)
{
if(pos<1||pos>GetLength(L))return false;
DNode *r=L,*p;//r遍历节点,p为待删除节点
while(--pos)
{
r=r->next;
}
p=r->next;
*e=p->data;
if(p->next==NULL)
{
r->next=NULL;
free(p);
return true;
}
r->next=p->next;
p->next->prior=r;
free(p);
return true;
}
int main()
{
DLinkList L=CreateList();
PrintList(L);
printf("头插入节点\n");
InsertListHead(L,-1);
PrintList(L);
printf("尾插法插入节点\n");
InsertListTail(L,-1);
PrintList(L);
printf("链表长度 %d\n",GetLength(L));
printf("在指定位置插入元素\n");
InsertPosition(L,5,-99);
PrintList(L);
printf("删除指定位置元素\n");
int *e;
DeletePosition(L,5,e);
printf("删除元素为:%d\n",*e);
PrintList(L);
return 0;
}
双向链表基本操作(C语言)
最新推荐文章于 2023-11-10 12:58:42 发布