c/c++ 双向链表 创建 插入 删除

来源:互联网 发布:mac自带快捷键怎么设置 编辑:程序博客网 时间:2024/06/07 18:47

同单链表的操作方法类似,不过在结点中加入了一个指向结点前驱的指针。

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <conio.h>using namespace std;typedef struct student{    int data;    struct student *next;    struct student *pre;}dnode;dnode* create();dnode* delNode(dnode* head, int num);dnode* instNode(dnode* head, int num);void searchmid(dnode* head,dnode* mid);void print(dnode* head);dnode* create(){    dnode *head;    head = (dnode*)malloc(sizeof(dnode));    head->data=0;    head->pre=nullptr;    head->next=nullptr;    int num=1;    while(num!=0)    {        cout << "Please input the data: ";        cin >> num;        instNode(head, num);    }    cout << "head data: " << head->data << endl;    return head;}dnode* delNode(dnode* head, int num){    dnode* p1;    p1=head;    while(num!=p1->data && p1->next!=nullptr)    {        p1=p1->next;    }    if(num == p1->data)    {        if(p1 == head)        {            head=head->next;            head->pre=nullptr;            free(p1);        }        else if(p1->next == nullptr)        {            p1=p1->pre;            p1->next=nullptr;            free(p1);        }        else        {            p1->next->pre=p1->pre;            p1->pre->next=p1->next;        }    }    else    {        cout << num << " could not found!!!" << endl;    }    return head;}dnode* instNode(dnode* head, int num){    dnode *p0,*p1;    p1=head;    p0=(dnode*)malloc(sizeof(dnode));    p0->data=num;    while((p0->data > p1->data) && (p1->next != nullptr))    {        p1=p1->next;    }    if(p0->data <= p1->data)    {        if(p1==head)        {            p0->next=p1;            p1->pre=p0;            head=p0;        }        else        {            p1->pre->next=p0;            p0->next=p1;            p0->pre=p1->pre;            p1->pre=p0;        }    }    else    {        p1->next=p0;        p0->pre=p1;        p0->next=nullptr;    }    return head;}void searchmid(dnode* head,dnode* mid){    dnode* temp = head;    while(head->next->next != nullptr)    {        head = head->next->next;        temp = head->next;        mid = temp;    }}void print(dnode* head){    while(head->next!=nullptr)    {        cout << head->data << endl;        head=head->next;    }    cout << head->data << endl;}int main(){    dnode* head;    int del_num,inst_num;    head = create();    print(head);    cout << "Input number would be deleted: ";    cin >> del_num;    head = delNode(head,del_num);    print(head);    cout << "Insert number would be inserted: ";    cin >> inst_num;    head = instNode(head,inst_num);    print(head);    return 0;}


阅读全文
1 0
原创粉丝点击