雙向鏈表(新版)

#include<iostream>
#include<stdlib.h>
using namespace std;
#define error -1

typedef struct Lnode
{
    int data;
    struct Lnode *prior;
    struct Lnode *next;
} LNode;

void listInsertIntoTail(Lnode *&h,int data);


void listInit(Lnode *&head)
{
    head->prior=NULL;
    head->next=NULL;
}

void listCreateByHead(Lnode *&h)//create a list by inserting into the head always
{
    for(int i=0; i<6; i++)
    {
        listInsertIntoTail(h,i);
    }
}

void listInsertIntoTail(Lnode *&h,int data)//insert data into tail
{
    Lnode *newnode=(Lnode*)malloc(sizeof(Lnode));
    newnode->data=data;
    newnode->next=NULL;

    Lnode *temp=h;
    while(temp->next!=NULL)
    {
        temp=temp->next;
    }

    newnode->prior=temp;
    temp->next=newnode;

    temp=NULL;
    newnode=NULL;
}

void deleteElem(Lnode *&h,int x)//delete the Element whose data equals x
{
    Lnode *temp1,*temp2;
    temp1=h;
    while(temp1->next->data!=x)//to find whose next node's data is x
    {
        temp1=temp1->next;
        if(temp1->next==NULL)//now, temp1 is the last node,it should break or it will leads to error.
        {
            break;
        }
    }
    if(temp1->next->data==x)
    {
        temp2=temp1->next;//to record the one needs to be deleted

        temp1->next->next->prior=temp1;
        temp1->next=temp1->next->next;//adjust the list
        free(temp2);//delete node x
    }
    else
    {
        cout<<x<<" node dose not exist."<<endl;
    }
    temp1=NULL;
    temp2=NULL;
}

void listUpdate(Lnode *&h,int oldvlue,int newvalue)//replace old with new
{
    Lnode *temp=h;
    while(temp!=NULL)
    {
        if(temp->data==oldvlue)
        {
            temp->data=newvalue;
        }
        temp=temp->next;
    }
    temp=NULL;
}

int findElem(Lnode *h,int x)//return x's position
{
    Lnode *temp=h;
    int position=0;
    while(temp->data!=x)
    {
        temp=temp->next;
        position++;
        if(temp==NULL)
        {
            break;
        }
    }
    if(temp->data==x)
    {
        return position;
    }
    else
    {
        return error;
    }
    temp=NULL;
}

void listDestroy(Lnode *&h)//release h's space
{
    Lnode *temp=h->next;
    while(temp!=NULL)
    {
        free(h);
        h=temp->next;
        temp=temp->next;
    }
    free(h);
    cout<<"List is destroyed."<<endl;
}

void printstate(Lnode *h)
{
    h=h->next;
    while(h!=NULL)
    {
        cout<<h->data<<" ";
        h=h->next;
    }
    cout<<endl;
}


int main()
{
    Lnode *h=(Lnode*)malloc(sizeof(Lnode));
    listInit(h);

    listCreateByHead(h);
    printstate(h);

    deleteElem(h,0);
    printstate(h);

    listUpdate(h,2,-1);
    printstate(h);

    cout<<findElem(h,-1)<<endl;

    listDestroy(h);
    h=NULL;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章