双链表 double linked list

13 篇文章 0 订阅
1 篇文章 0 订阅
</pre><pre>

typedef struct Node{
    int key;
    Node *prev, *next;
}Node, *pNode;

typedef struct List{    //定义链表类
    pNode firstNode;    //List句柄(handle)
    List();
    void insert(pNode x);
}List;

List::List(){
    firstNode = NULL;
}

void List::insert(pNode x){
    if(firstNode == NULL)
        firstNode = x;
    else{                           //寻找插入位置loc
        pNode parent = firstNode;
        pNode loc = parent;
        while(loc != NULL && x->key > loc->key){
            parent = loc;
            loc = loc->next;
        }
        if(loc == firstNode){       //若loc为头节点
            pNode temp = firstNode;
            firstNode = x;
            x->next = temp;
            temp->prev = x;
        }
        else if(loc == NULL){      //若loc为尾节点
            parent->next = x;
            x->prev = parent;
        }
        else{                   //若loc为中间节点
            x->next = parent->next;
            parent->next = x;
            x->next->prev = x;
            x->prev = parent;
        }
    }
}


测试:

void test(){
    List lis;
    Node x = {4,NULL,NULL};
    Node x1 = {9,NULL,NULL};
    Node x2 = {2,NULL,NULL};
    Node x3 = {5,NULL,NULL};
    lis.insert(&x);
    lis.insert(&x1);
    lis.insert(&x2);
    lis.insert(&x3);
    pNode temp = lis.firstNode;
    while(temp != NULL){
        cout<<temp->key<<"  ";
        temp = temp->next;
    }
    cout<<endl;
}

int main() {
    test();     //输出:2 4 5 9
    return 0;
}

设定firstNode不为NULL,而是minus infinity,则在调用handel入口时,必须为firstNode分配内存!

新的构造函数List():

List::List(){
    firstNode = (pNode)malloc(sizeof(Node));    //重要!!在函数外调用firstNode必须要在Construction函数中分配内存!!!!
    firstNode->key = -1;
    firstNode->next = NULL;
}
新的插入函数:

void List::insert(pNode x){
    pNode it = firstNode;
    pNode par = firstNode;
    while (it != NULL && it->key < x->key) {
        par = it;
        it = it->next;
    }
    x->next = par->next;
    par->next = x;
    x->prev = par;
    if(x->next != NULL)
        x->next->prev = x;
}
测试:

void test(){
    List lis;
    pNode temp = lis.firstNode;   //要求lis.firstNode必须已分配内存,在List()用malloc函数

    Node x = {4,NULL,NULL};
    Node x1 = {9,NULL,NULL};
    Node x2 = {2,NULL,NULL};
    Node x3 = {5,NULL,NULL};
    lis.insert(&x);
    lis.insert(&x1);
    lis.insert(&x2);
    lis.insert(&x3);
    while(temp != NULL){
        cout<<temp->key<<"  ";
        temp = temp->next;
    }
    cout<<endl;
}
int main() {
    test();     //输出:-1 2 4 5 9
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值