有了单链表的编写经验,双链表变得格外容易。点击看前一篇-单链表
下面是代码:
#include<stdio.h>
#include<stdlib.h>
#define E int
typedef struct node {E element;struct node* pre;struct node* next;
}node;
void initialise(node* head) {//初始化头节点head->element = 0;head->next = NULL;head->pre = NULL;
}
int add_node(node* head,int index,E ele) {node* tem = head->next;//先将下一节点指针给一个临时变量if (index < 1)return -1;while (--index && tem != NULL) {head= tem;tem = tem->next;//移动指向下一节点}if (index == 0 && tem == NULL) {node* ptr = (node*)malloc(sizeof(node));if (ptr == NULL)return -1;ptr->element = ele;ptr->pre = head;head->next = ptr;ptr->next = NULL;return 1;}else if (tem != NULL) {//在中间添加的情况node* ptr = (node*)malloc(sizeof(node));ptr->element = ele;ptr->pre = head;head->next = ptr;ptr->next = tem;tem->pre = ptr;return 1;}return -1;//没有这个位置的节点
}
print_node(node* head) {while (head->next != NULL) {head = head->next;//节点指针移动printf("%d\n", head->element);}
}
int del_node(node* head, E ele) {node* tem = head->next;int count = 0;while (tem != NULL) {if (tem->element == ele) {head->next = tem->next;if (tem->next != NULL)tem->next->pre = head;//如果是删的最后一个元素,这句话不用执行count++;}head = tem;tem = tem->next;//节点指针移动}if(!count)return -1;return 1;
}
node* find_node(node* head, E ele) {head = head->next;//先移动头节点指针while (head != NULL) {if (head->element == ele) {return head;}head = head->next;//移动到下一节点}
}
node* modif_node(node* head, int index,E ele) {head = head->next;//先移动头节点指针if (index < 1)return NULL;while (--index && head != NULL) {head = head->next;//继续移动到需要位置}if (head == NULL)return NULL;head->element = ele;return head;
}
int main() {node head;initialise(&head);for (int i = 1; i <= 8; i++) {add_node(&head, 1, 20*i);}add_node(&head, 9, 520);print_node(&head);printf("----------\n");del_node(&head, 160);print_node(&head);printf("----------\n");node* find = find_node(&head, 520);//找这个数据的前一个数据printf("%d\n", find->pre->element);printf("%d\n", find->element);printf("----------\n");node* mod = modif_node(&head,9 ,999);if(mod!=NULL)printf("%d\n", mod->element);printf("----------\n");print_node(&head);return 0;
}