#include <stdio.h> #include <stdlib.h> #include "doubly.h" 带头双向链表 typedef struct DoublyNode { DoublyNode*next; DoublyNode*prior; int data; }DoublyNode; 头插创建 DoublyNode* HeadCreateLinkList(){ DoublyNode*head = (DoublyNode*)malloc(sizeof(DoublyNode)); head->next = NULL; head->prior = NULL; for (int i=0;i<10;i++) { DoublyNode*p = (DoublyNode*)malloc(sizeof(DoublyNode)); p->data = i; p->next = head->next; if (head->next!=NULL) { head->next->prior = p; } p->prior = head; head->next = p; } return head; } 尾插创建 DoublyNode* TailCreateLinkList() { DoublyNode*head = (DoublyNode*)malloc(sizeof(DoublyNode)); head->next = NULL; head->prior = NULL; DoublyNode*s=head; for (int i=0;i<10;i++) { DoublyNode*p = (DoublyNode*)malloc(sizeof(DoublyNode)); p->data = i; p->next =NULL; p->prior = s; s->next = p; s=p; } return head; } 插入指定节点前 void InsertNodeLinkList(DoublyNode*head,int elem,int val) { if (head==NULL||head->next==NULL) { return ; } DoublyNode*p=head->next; while(p!=NULL) { if (p->data==elem){ DoublyNode*q = (DoublyNode*)malloc(sizeof(DoublyNode)); q->data = val; q->next = p; q->prior = p->prior; if (p->prior!=NULL) { p->prior->next = q; } p->prior=q; } p=p->next; } } 打印 void PrintLinkList(DoublyNode*head){ if (head==NULL||head->next==NULL) { return; } DoublyNode*p=head->next; while(p!=NULL) { printf("%d ",p->data ); p=p->next; } printf("\n"); } 长度 int GetLinkListLenth(DoublyNode*head) { if (head==NULL||head->next==NULL){ return 0; } DoublyNode*p=head->next; int count = 0; while(p!=NULL){ count++; p=p->next; } return count; } 删除指定节点 void DeleteLinkList(DoublyNode*head,int elem){ if (head==NULL||head->next==NULL){ return ; } DoublyNode*p=head->next; while(p!=NULL) { if (p->data == elem) { DoublyNode*q = p; if (p->prior!=NULL) { p->prior->next = p->next; } if (p->next!=NULL) { p->next->prior = p->prior; } free(q); } p=p->next; } } 释放 void DestoryLinkList(DoublyNode*head) { if (head==NULL||head->next==NULL){ return ; } DoublyNode*p=head->next; while(p!=NULL) { DoublyNode*q = p; head->next=p->next; if (p->next!=NULL) { p->next->prior=p->prior; } free(q); p=p->next; } //free(head); 释放头 } //逆置 从第二个开始逆置 void ReverseLinkList(DoublyNode*head) { if (head==NULL||head->next==NULL||head->next->next==NULL){ return ; } DoublyNode*p=head->next; DoublyNode*q=p->next; while(q!=NULL) { p->next=q->next; if (q->next!=NULL) { q->next->prior=p; } q->next= head->next; q->prior = head; if (head->next!=NULL) { head->next->prior = q; } head->next = q; q=p->next; } } /* //从第一个开始逆置 void ReverseLinkList(DoublyNode*head) { if (head==NULL||head->next==NULL||head->next->next==NULL){ return ; } DoublyNode*p=head->next; DoublyNode*q; while(p!=NULL) { q=p; p->prior->next = p->next; if (p->next!=NULL) { p->next->prior=p->prior; } p=p->next; q->next= head->next; q->prior = head; head->next->prior = q; head->next = q; } } */
带头双向链表实现
最新推荐文章于 2022-03-13 15:07:28 发布