关闭

C语言实现双链表基本操作(创建、查找、插入、删除)

标签: 源代码c语言
337人阅读 评论(0) 收藏 举报
分类:
//双链表基本操作
#include<stdio.h>
#include<stdlib.h>

typedef int ElemType;
typedef struct DNode
{
ElemType data;
struct DNode *prior,*next;

}DNode,*DLinkList;

//尾插法建立链表
DLinkList CreatDList(DLinkList &la)
{

int x;
la = (DLinkList)malloc(sizeof(DNode));
la->next = NULL;
DNode *s,*r=la;
scanf("%d",&x);
while(x!=9999)
{

s = (DNode *)malloc(sizeof(DNode));
s->data = x;
r->next = s;
s->prior = r; //连接前驱
r = s;
scanf("%d",&x);

}
r->next = NULL;
return la;
}

//按序号查找节点
DNode *GetDElem(DLinkList L,int i)
{

int j = 1;
DNode *p = L->next;
if(i<1)
return NULL;
while(p&&j<i)
{
p = p->next;
j++;
}

return p;
}


//双链表的插入操作
DNode *InsertDElem(DLinkList L,int x,int i)
{
DNode *p = GetDElem(L,i);
DNode *s = (DNode*)malloc(sizeof(DNode));
s->data = x;
s->next = p->next;
p->next->prior = s;
s->prior = p;
p->next = s;
return p;
}

//双链表的删除操作
DNode *DeleteDElem(DLinkList L,int i)
{
DNode *p = GetDElem(L,i-1);
DNode *q = p->next;
p->next = q->next;
q->next->prior = p;
free(q);

return p;

}

void main()
{

DLinkList la;
DNode *m;
CreatDList(la);
//m = InsertDElem(la,54,3);
m = DeleteDElem(la,3);
printf("%d,%d,%d\n",m->prior->data,m->data,m->next->data);

}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:16961次
    • 积分:247
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:21篇
    • 译文:0篇
    • 评论:0条
    文章分类