双向链表的插入删除和查询

实现双向链表的插入删除和查询,并写出测试用例。


#include <iostream>
#include <cstdlib>

using namespace std;



/***
*实现双向链表的插入、查找、删除
*xx笔试算法题
***/

typedef struct Node
{
    int data;
    struct Node * next;
    struct Node * prev;
}Node;

/**在链表h第pos个节点前插入值为v的节点,如果不存在
第pos个节点,则插入在尾部*/
Node * dlinsert(Node *h, int pos, int v)
{
    int i=0;
    Node * t=h;
    Node * pre = h;
    while(i<pos && t )
    {
        i++;
        pre = t;
        t = t->next;
    }
    Node * n = (Node*)malloc(sizeof(Node));
    n->data = v;
    if(h==0)///空表
    {
        n->prev = 0;
        n->next = 0;
        return n;
    }
    if(t!=0)///不在尾部
    {
        n->next = t;
        n->prev = pre;
        t->prev = n;
        pre->next=n;
    }
    else///insert at tail
    {
        pre->next = n;
        n->prev = pre;
        n->next = 0;
    }
    return h;
}

void print(Node *h)
{
    cout<<"order:"<<endl;
    while(h)
    {
        cout<<h->data<<" ";
        h = h->next;
    }
    cout<<endl;
}

void printReverse(Node *h)
{
    cout<<"reverse order:"<<endl;
    while(h&&h->next)
    {
        h = h->next;
    }
    while(h)
    {
        cout<<h->data<<" ";
        h = h->prev;
    }
    cout<<endl;
}

/*** 查找第一个值为v的节点,并返回该节点的指针*/
Node * query(Node *h, int v)
{
    while(h&&h->data!=v)
        h = h->next;
    return h;
}

/**删除值为v的第一个节点,并置位flag*/
Node * dldelete(Node *h, int v, int *flag)
{
    Node * d = query(h,v);
    if(d)///delete node d
    {
        cout<<"find "<<endl;
        if(d->next==0)///last node
        {
            d->prev->next = 0;
        }
        else if(d->prev==0)///first node
        {
            d->next->prev=0;
            h = d->next;///for return
        }
        else
        {
            d->next->prev = d->prev ;
            d->prev->next = d->next;
        }
        free(d);
        *flag = 1;
        return h;
    }
    else
    {///failed delete
        cout<<"not find "<<endl;
        *flag = 0;
        return h;
    }
}


int main()
{
    Node *h=0;
    h=dlinsert(h,1,9);
    print(h);
    printReverse(h);

    h=dlinsert(h,2,8);
    print(h);
    printReverse(h);

    h=dlinsert(h,1,3);
    print(h);
    printReverse(h);

    h=dlinsert(h,1,5);
    print(h);
    printReverse(h);

    ///test query
    int v = 1;
    Node * s=query(h,v);
    if(s)
        cout<<s<<"->"<<s->data<<endl;
    else
        cout<<"cannot find "<<v<<" in the list."<<endl;

    ///test delete
    int st=0;
    int * flag =&st ;
    v = 8;
    h = dldelete(h,v,flag);
    cout<<"delete state:"<<*flag<<endl;
    print(h);
    printReverse(h);

    return 0;
}


当时不知道怎么2了,一直在考虑循环链表的头和尾指针为题。。。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值