c/c++双方向チェーンテーブル作成挿入削除

3125 ワード

単一チェーンテーブルと同様の操作方法ですが、ノードにはノードの前駆を指すポインタが追加されています.
#include 
#include 
#include 
#include 
#include 
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;
}