双向链表的结构中有两个指针分别指向上一个节点和下一个节点,可以更方便的访问数据
1节点
typedef struct Node {
int data;
struct Node *next;//指向下一个节点
struct Node *prior;//指向上一个节点
}Node;
2创建双向链表
```Status creatList(Linklist *p){
*p = (Linklist )malloc(sizeof(Node));
if (*p == NULL) {
printf("链表创建失败!");
return 0;
}
(*p)->data = 0;
(*p)->next = NULL;
(*p)->prior = NULL;
Linklist b = (*p);
for (int i = 0; i < 10; i++) {
//创建一个新的节点
Linklist node = malloc(sizeof(node));
node->next = NULL;
node->prior= NULL;
node->data = i;
b->next = node;
node->prior = b;
b = b->next;
}
return 1;
}
3插入
Status ListInsert(Linklist *p,int data , int index){
if (*p == NULL) {
printf("链表不存在");
return 0;
}
Linklist temp,newNode,targetNode;
//新建节点
newNode = malloc(sizeof(Node));
newNode->next = NULL;
newNode->prior = NULL;
newNode->data = data;
temp = (*p)->next;
for (int i = 0; i<index && temp; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("下标越界");
return 0;
}
if (temp->next == NULL) {
temp->next = newNode;
newNode->prior = temp;
}else{
targetNode = temp->next;
temp->next = newNode;
newNode->prior = temp;
targetNode->prior = newNode;
newNode->next = targetNode;
}
return 1;
}
4删除
Status ListDel(Linklist *p , int index){
int i;
Linklist temp,target;
if (*p == NULL) {
printf("链表不存在");
return 0;
}
temp = (*p)->next;
for (int i = 0; i<index && temp; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("下标越界");
return 0;
}
if (temp->next == NULL) {
temp->prior->next = NULL;
free(temp);
}else{
target = temp->prior;
target->next = temp->next;
temp->next->prior = target;
free(temp);
}
return 1;
}
5遍历打印
void enumList(Linklist p){
printf("链表数据如下:\n");
Linklist temp;
temp = p;
while (p->next) {
printf("%5d",p->data);
p = p->next;
}
printf("\n");
}
网友评论