c语言:双向链表(head->data中存储长度)
1、链表的初始化、插入、删除、遍历、链表长度。
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node * previous;
struct node * next;
} Node;
Node * head=(Node*)malloc(sizeof(Node));
Node * tail=(Node*)malloc(sizeof(Node));
void init()
{
Node *current = head;
head->next = tail;
tail->previous = head;
head->data=0;
for(int i=1;i<=12;i++)
{
Node *new_node=(Node*)malloc(sizeof(Node));
new_node->data = i;
new_node->previous = current;
current->next = new_node;
new_node->next = tail;
tail->previous = new_node;
current = current->next;
head->data = ++(head->data);//head->data存下链表元素个数!
}
};
void insert1(int a)
{
Node * temp1=(Node*)malloc(sizeof(Node));
temp1->data = a;
Node * sec=tail->previous;
sec->next= temp1;
temp1->previous = sec;
temp1->next = tail;
tail->previous = temp1;
head->data = ++(head->data);//head->data存下链表元素个数!
};
void display()
{
//printf("%d | ",head->data);
for(Node* T=head->next;T != tail;T=T->next)
{
printf("%d ",T->data);
}
printf(" 链表长度:%d\n",head->data);
};
Node *find1(int a)
{
for(Node* T=head->next;T != tail;T=T->next)
{
if(T->data == a)
{
return T;
}
}
printf("元素中没有%d ",a);
return NULL;
};
void delete1(Node *a)
{
for(Node* T=head->next;T != tail;T=T->next)
{
if(T == a)
{
Node *T1=T->previous;
Node *T2=T->next;
T1->next = T2;
T2->previous = T1;
free(T);
head->data = --(head->data);//head->data存下链表元素个数!
return;
}
}
printf("元素删除失败\n");
return;
};
int main()
{
init();
display();
insert1(22);
display();
printf("%d\n",find1(100)?find1(100)->data:100);
delete1(find1(6));
display();
return 0;
}
/*
1 2 3 4 5 6 7 8 9 10 11 12 链表长度:12
1 2 3 4 5 6 7 8 9 10 11 12 22 链表长度:13
元素中没有100 100
1 2 3 4 5 7 8 9 10 11 12 22 链表长度:12
*/