#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* pre;
struct Node* next;
}Node;
Node* initList(){
Node* List=(Node*)malloc(sizeof(Node));
List->data=0;
List->pre=List;
List->next=List;
return List;
}
void headInsert(Node* List,int data){
Node* node=(Node*)malloc(sizeof(Node));
node->data=data;
if(List->data==0){//链表为空
//这里node和List赋值的先后顺序可以随意
List->next=node;
List->pre=node;
node->pre=List;
node->next=List;
}else{//链表不为空
//注意node和List赋值的先后顺序,顺序不同全错,为什么???
node->next=List->next;
node->pre=List;
List->next->pre=node;
List->next=node;
}
List->data++;
}
void tailInsert(Node* List,int data){
Node* node=(Node*)malloc(sizeof(Node));
Node* head=List;
head->data++;
node->data=data;
List=List->next;
while(List->next!=head){
List=List->next;
}
List->next=node;
head->pre=node;
node->next=head;
node->pre=List;
}
void delete(Node* List,int data){
List->data--;
Node* node=List->next;
while(node->data!=data){
node=node->next;
}
node->pre->next=node->next;
node->next->pre=node->pre;
free(node);
}
void printList(Node* List){
Node* node=List->next;
while(node!=List){
printf("%d->",node->data);
node=node->next;
}
printf("over!\n");
}
int main() {
Node* list=initList();
headInsert(list,1);
headInsert(list,2);
headInsert(list,3);
headInsert(list,4);
tailInsert(list,0);
tailInsert(list,5);
tailInsert(list,6);
tailInsert(list,7);
tailInsert(list,8);
delete(list,0);
delete(list,1);
delete(list,4);
delete(list,8);
printList(list);
printf("链表共有%d个节点",list->data);
return 0;
}
数据结构——双循环链表
于 2022-08-08 11:53:25 首次发布