C/C++ 知识点回顾 双向链表的创建、插入和删除

来源:互联网 发布:微信开放平台 php源码 编辑:程序博客网 时间:2024/06/05 22:36
#include<iostream>using namespace std;typedef struct student{int data;struct student *pre;struct student * next;//注意!!!!此处不能用dnode * next;} dnode;//输出void print(dnode *  head){if (head == NULL){return;}dnode * p = head;while (p){cout << p->data << ' ';p = p->next;}cout << endl;}//创建双向链表dnode * create(){dnode *head = (dnode *)malloc(sizeof(dnode));dnode *p = head, *q=NULL;//一定要初始化int n = 0;while (cin>>n&&n){q = (dnode *)malloc(sizeof(dnode));q->next = NULL;//一定要初始化q->data = n;q->pre = p;p->next = q;p = q;}head = head->next;head->pre = NULL;print(head);return head;}//双向链表删除节点dnode * del(dnode * head, int num){dnode *p = head;dnode *q = head;while (p->data != num&&p->next){p = p->next;}if (p->data == num){if (p == head){head = head->next;head->pre = NULL;free(p);}else if (p->next == NULL){q = p->pre;q->next = NULL;free(p);}else{q = p->pre;q->next = p->next;free(p);}}print(head);return head;}//双向链表插入结点dnode *insert(dnode * head, int num){dnode *p = head;dnode *q = head;q = (dnode*)malloc(sizeof(dnode));q->data = num;while (p->next&&q->data>p->data){p = p->next;}if (p->data<q->data){p->next = q;q->pre = p;q->next = NULL;}else{if (p == head){q->next = head;q->pre = NULL;head = q;}else{p->pre->next = q;q->pre = p->pre;q->next = p;}}print(head);return head;}int main(){dnode * head = create();head = insert(head, 7);head = del(head, 7);};


0 0
原创粉丝点击