双向链表
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<stdlib.h>
typedef struct Node
{
Node* pre;
Node* next;
}node;
typedef struct Common_list
{
node head;
int length;
}common_list;
common_list*creat_double_list()
{
common_list* old = (common_list*)malloc(sizeof(common_list));
if (old == nullptr)
{
printf("空间错误!!!\n");
return nullptr;
}
old->head.next = nullptr;
old->head.pre = nullptr;
old->length = 0;
return old;
}
void insert_list(common_list** old, node*input, int pos)
{
common_list* old_list = (common_list*)*old;
node* current = &old_list->head;
node* next = current->next;
input->next = next;
current->next = input;
input->pre = current;
if (next!=nullptr)
{
next->pre = input;
}
if (current == (node*)old_list)
{
input->pre = nullptr;
}
old_list->length++;
}
node* show_list(common_list*old,int pos)
{
if (old == nullptr || pos < 0 || pos >= old->length)
{
printf("位置错误!!!\n");
return nullptr;
}
common_list*temp_show = old;
node* current = &temp_show->head;
for (int i = 0; i < pos; i++)
{
current = current->next;
}
return current->next;
}
node* delete_list(common_list**old, int pos)
{
common_list*temp_del = *old;
if (temp_del == nullptr || pos<0 || pos>= temp_del->length)
{
printf("位置错误!!!\n");
return nullptr;
}
node* current = &temp_del->head;
for (int i = 0; i < pos; i++)
{
current = current->next;
}
node* del = current->next;
node* next = del->next;
current->next = next;
if (next != nullptr)
{
next->pre = current;
if (current == (node*)temp_del)
{
printf("要删除的节点是第一个!!!\n");
next->pre = nullptr;
}
}
temp_del->length--;
}
void clear_list(common_list**old)
{
common_list* temp_clear = *old;
free(temp_clear);
temp_clear = nullptr;
printf("链表清空!!!\n");
}
int length_list(common_list*old)
{
if (old == nullptr)
{
printf("空间错误!!!\n");
return -1;
}
return old->length;
}
typedef struct User
{
node head;
int price;
char name[16];
}user;
int main()
{
user*get1;
user u1;
u1.price = 1999;
strcpy_s(u1.name, "iQOO7");
common_list*old = creat_double_list();
insert_list(&old,(node*)&u1,0);
user u2;
u2.price = 2999;
strcpy_s(u2.name,"iQOO5");
insert_list(&old, (node*)&u2, 0);
user u3;
u3.price = 3999;
strcpy_s(u3.name,"iQOO3");
insert_list(&old, (node*)&u3, 0);
user u4;
u4.price = 4999;
strcpy_s(u4.name, "iQOO");
insert_list(&old, (node*)&u4, 0);
printf("\n");
for (int i = 0; i < length_list(old); i++)
{
get1 = (user*)show_list(old, i);
printf("第【%d】个手机!\n",i+1);
printf("name = %s\n", get1->name);
printf("price = %d\n", get1->price);
}
printf("\n");
delete_list(&old,0);
for (int i = 0; i < length_list(old); i++)
{
get1 = (user*)show_list(old, i);
printf("第【%d】个手机!\n", i + 1);
printf("name = %s\n", get1->name);
printf("price = %d\n", get1->price);
}
printf("\n");
delete_list(&old, 2);
for (int i = 0; i < length_list(old); i++)
{
get1 = (user*)show_list(old, i);
printf("第【%d】个手机!\n", i + 1);
printf("name = %s\n", get1->name);
printf("price = %d\n", get1->price);
}
clear_list(&old);
get1 = (user*)show_list(old, 0);
return 0;
}