#include <stdio.h>
#include <stdlib.h>
typedef struct line {
struct line *prior;
int data;
struct line *next;
}line;
/*创建双向链表并初始化*/
line * initLine(line * head) {
head = (line *)malloc(sizeof(line));
head->prior = NULL;
head->next = NULL;
head->data = 1;
line * list = head;
for(int i = 2; i <= 3; i++) {
line *body = (line *)malloc(sizeof(line));
body->prior = NULL;
body->next = NULL;
body->data = i*10;
list->next = body;
body->prior = list;
list = list->next;
}
return head;
}
/*在双向链表中插入节点*/
line * insertLine(line *head,int data,int add) {
/*新建一个数据域为data的节点*/
line *temp = (line *)malloc(sizeof(line));
temp->data = data;
temp->prior = NULL;
temp->next = NULL;
/*插入表头*/
if (add == 1) {
//这里调换是否可以
temp->next = head;
head->prior = temp;
head = temp;
printf("头插\n");
}else {
line *body = head;
/*找到要插入位置的前一个节点*/
for (int i = 1; i < add - 1;i++) {
body = body->next;
}
/*判断条件为真,说明插入位置为链表尾部*/
if (body->next == NULL) {
temp->prior = body;
body->next = temp;
printf("尾插\n");
}else{
/*
*[>错误使用<]
*temp->next = body->next;
*temp->prior = body;
*body->next = temp;
*body->next->prior = temp; //这两行前后的顺序,导致无法通过正确插入位置的前一个节点找到插入节点后的节点位置。
*/
temp->next = body->next;
temp->prior = body;
body->next->prior = temp;
body->next = temp;
}
}
return head;
}
/*在双向链表中删除节点*/
line *delLine(line * head, int data) {
line * temp = head;
while(temp) {
if(temp->data == data) {
/*头删*/
if(temp->prior == NULL) {
temp->next->prior = NULL;
head = temp->next;
free(temp);
return head;
/*尾删*/
}else if(temp->next == NULL) {
temp->prior->next = NULL;
free(temp);
return head;
}else {
temp->prior->next = temp->next;
temp->next->prior = temp->prior;
printf("debug: %s,%d\n",__FUNCTION__,__LINE__);
free(temp);
return head;
}
}
temp = temp->next;
}
printf("链表中无该数据元素!");
return head;
}
/*输出链表*/
void displayList(line *head) {
line *temp = head;
while(temp) {
if(temp->next == NULL) {
printf("%d\n",temp->data);
}else {
printf("%d->",temp->data);
}
temp = temp->next;
}
}
int main(void)
{
line *my_list = NULL;
my_list = initLine(my_list);
displayList(my_list);
my_list = insertLine(my_list,55,1);
displayList(my_list);
my_list = insertLine(my_list,56,5);
displayList(my_list);
my_list = insertLine(my_list,58,3);
my_list = insertLine(my_list,589,3);
my_list = insertLine(my_list,111,5);
displayList(my_list);
my_list = delLine(my_list,55);
displayList(my_list);
my_list = delLine(my_list,56);
displayList(my_list);
my_list = delLine(my_list,58);
displayList(my_list);
my_list = delLine(my_list,589);
displayList(my_list);
return 0;
}
C语言编写一个双向链表
最新推荐文章于 2024-04-19 19:29:36 发布