双链表跟单链表相比,多维护了一个指针,这个指针指向结点的前驱结点。

#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef struct Node
{
    struct Node *next;
    struct Node *prior;
    int elem;
}*Dlinklist;

Dlinklist creat(Dlinklist &L)
{
    L = new Node;
    int data;
    Node *p,*q;
    p = new Node;
    L->next = p;
    cin>>data;
    p->elem = data;
    while(cin>>data&&data != -1)
    {
        q = new Node;
        q ->elem = data;
        p ->next = q;
        q ->prior = p;
        p = p->next;
    }
    p ->next = NULL;
    return L;
}

Node* findElem(Dlinklist L,int index)
{
    int j = 1;
    Node *p = L ->next;
    while(j<index&&p)
    {
        j++;
        p = p->next;
    }
    return p;
};
int findIndex(Dlinklist &L,int x)
{
    int j = 1;
    Node *p = L->next;
    while(p&&(p->elem != x))
    {
        j++;
        p = p->next;
    }
    return j;
};

void insert(Dlinklist &L,int index,int x)
{
    if(index == 1)
    {
        Node *p = new Node;
        p->elem = x;
        p->next = L->next;
        L->next->prior = p;
        L->next = p;
    }
    else
    {
        Node *p = findElem(L, index-1);
        Node *q = new Node;
        q ->elem = x;
        q->next = p->next;
        p->next->prior = q;
        q->prior = p;
        p->next = q;
    }
};
void remove(Dlinklist &L,int index)
{
    Node *p = findElem(L, index-1);
    Node *q = p->next;
    p->next = q->next;
    q->next->prior = p;
    free(q);
}
void printDList(Dlinklist &L)
{
    Node *p = L->next;
    while(p)
    {
        cout<<p->elem<<" ";
        p = p->next;
    }
    cout<<endl;
}
int main(int argc, const char * argv[])
{
    Dlinklist L;
    Dlinklist DL = creat(L);
    Node *p = findElem(DL, 6);
    cout<<p->elem<<endl;
    printDList(DL);
    insert(DL, 2, 1000);
    remove(DL,3);
    printDList(DL);
    return 0;
}

 

 posted on 2014-06-02 17:06  Clivia_zhou  阅读(146)  评论(0编辑  收藏  举报