#include <stdio.h>
#include <stdlib.h>
struct list_node_t{
struct list_node_t *pre;
struct list_node_t *next;
union {
int data;
int index;
}u_data;
};
void print_list(struct list_node_t *head)
{
struct list_node_t *cur;
int i = 0;
if((head == NULL) && (head->next == NULL))
printf("list is null\n");
else{
printf("list node is %d \n",head->u_data.index);
for (cur = head->next;cur!= NULL; cur = cur->next){
printf("index:%d data %d\n", i, cur->u_data.data);
i++;
}
}
}
struct list_node_t *create_list(void)
{
struct list_node_t *head = (struct list_node_t *)malloc(sizeof(struct list_node_t));
if(head == NULL)
printf("%s: error\n",__func__);
head->next = NULL;
head->pre = NULL;
head->u_data.index = 0;
return head;
}
struct list_node_t *create_node(int data)
{
}
struct list_node_t *find_data_list(struct list_node_t *head , int data)
{
struct list_node_t *cur= NULL;
if((head == NULL)&&(head->next == NULL))
printf("list is null\n");
for (cur = head->next;cur != NULL; cur = cur->next)
{
if(cur->u_data.data == data)
break;
}
if(cur == NULL){
printf("data is not in list\n");
return cur;
}
return cur;
}
struct list_node_t *insert_data_list(struct list_node_t *head, int data)
{
struct list_node_t *node = NULL;
node = (struct list_node_t *)malloc(sizeof(struct list_node_t));
if(node == NULL)
printf("%s:%d malloc error \n",__func__, __LINE__);
node->u_data.data = data;
node->next = NULL;
node->pre = NULL;
if (head->next == NULL){
head->next = node;
node->pre = head;
}
else
{
node->next = head->next;
node->pre = head->next->pre;
head->next->pre = node;
head->next = node;
}
head->u_data.index++;
return head;
}
struct list_node_t *del_data_list(struct list_node_t *head, int data)
{
struct list_node_t *pre = NULL;
struct list_node_t *cur = NULL;
#if 1
for(cur = head->next,pre = head; cur != NULL; cur= cur->next)
{
if(cur->u_data.data != data){
pre = cur;
}
else
{
pre->next = cur->next;
if(cur->next != NULL)
cur->next->pre = cur->pre;
}
}
#else
cur = find_data_list(head,data);
pre = cur->pre;
pre->next = cur->next;
if(cur->next != NULL)
cur->next->pre = cur->pre;
#endif
free(cur);
head->u_data.index--;
return head;
}
void print_list1(struct list_node_t *head)
{
struct list_node_t *cur;
int i = 0;
cur = find_data_list(head,1);
for(; cur != NULL; cur = cur->pre)
printf("%d\n", cur->u_data.data);
}
int main()
{
int i ;
struct list_node_t *head = NULL;
head = create_list();
for(i = 0; i < 10; i++)
{
insert_data_list(head, i+1);
}
print_list(head);
head = del_data_list(head, 5);
print_list(head);
return 0;
}
实验结果
root@opcv-VirtualBox:/home/opcv/test_module/data_st/list/double_list# ./llist
list node is 10
index:0 data 10
index:1 data 9
index:2 data 8
index:3 data 7
index:4 data 6
index:5 data 5
index:6 data 4
index:7 data 3
index:8 data 2
index:9 data 1
list node is 9
index:0 data 10
index:1 data 9
index:2 data 8
index:3 data 7
index:4 data 6
index:5 data 4
index:6 data 3
index:7 data 2
index:8 data 1