#include<stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct DNode {
ElemType data; //数据域
struct DNode *prior, *next;
} DNode;
//尾插法创建双链表
DNode* DList_TailInsert(DNode *L) {
int x;
L = (DNode*) malloc(sizeof(DNode)); //创建头结点
DNode *s;
DNode *r = L; //r为表尾指针
scanf("%d", &x); //输入节点的值
while (x != 999) { //输入999表示结束
s = (DNode*) malloc(sizeof(DNode));
s->data = x;
s->prior = r;
r->next = s;
//printf("hello world\n");
r = s; //r指向新的表尾节点
scanf("%d", &x);
}
r->next = NULL; //尾结点的指针置为空
return L;
}
//按序号查找结点
DNode* GetElem(DNode *L, int i) {
int j = 1;
DNode *p;
p = L->next; //将头结点指针next赋给p,指针p相当于指向第一个数据结点(非头结点)
if (i == 0)
return L;
if (i < 1)
return NULL;
while (p != NULL && j < i) { //当i等于1时,直接返回p
p = p->next;
j++;
}
return p;
}
//双链表的插入操作
DNode* DListInsert(DNode *L, int i, int e) {
DNode *p;
p = GetElem(L, i); //查找插入位置的结点
DNode *s;
s = (DNode*) malloc(sizeof(DNode));
s->data = e;
s->prior = p->prior;
s->next = p;
p->prior->next = s;
return L;
}
//双链表的删除操作
DNode* DListDelete(DNode *L, int i) {
DNode *p;
p = GetElem(L, i); //查找删除位置的结点
p->prior->next = p->next;
p->next->prior = p->prior->next;
free(p);
return L;
}
//遍历双链表
void PrintDList(DNode *L) {
//printf("nihao\n");
DNode *p;
p = L->next;
//printf("nihao1");
while (p->next != NULL) {
//printf("nihao");
printf("%d ", p->data);
p = p->next;
if (p->next == NULL) { //输出最后一个元素
printf("%d ", p->data);
}
}
}
int main() {
DNode L;
DNode *L1 = DList_TailInsert(&L);
PrintDList(L1);
printf("\n");
DNode *L2 = DListInsert(L1, 1, 0);
PrintDList(L2);
printf("\n");
DNode *L3 = DListDelete(L2,1);
PrintDList(L3);
}
双链表的基本操作 C语言版
最新推荐文章于 2024-08-16 10:42:04 发布