双链表的操作

#include <iostream>
#define NIL 0
using namespace std;

struct list
{
    int data;
    list *last;
    list *next;
    list(int data)
    {
        this->data=data;
        this->last=NIL;
        this->next=NIL;
    }
};

struct Link
{
  list *head;
};

INSERT(Link &L,list &x) //将x插入链表L中
{
    x.next=L.head;
    if(L.head != NIL) L.head->last=&x;
    L.head=&x;
    x.last=NIL;
}

DELETE_ELEMENT(Link &L,list &x) //删除L链表中的x元素
{
    if(x.last != NIL) x.last->next=x.next;
    else L.head=x.next;
    if(x.next != NIL) x.next->last=x.last;
}

int SEARCH(Link &L,int key) //寻找链表中具有key关键字的元素,返回其位置
{
    int i=1;
    list *p;
    p=L.head;
    while(p)
    {
        if(p->data == key) return i;
        p=p->next;
        i++;
    }
    return 0;
}

int DELETE_KEY(Link &L,int key)  //删除L链表中具有key关键字的元素,首先需要寻找此元素
{
    int temp;
    temp=SEARCH(L,key);
    if(temp == 0)
    {
        cout << "not found" << endl;
        return 0;
    }
    else
    {
        list *p;
        p=L.head;
        while(--temp) p=p->next;

        if(p->last != NIL) p->last->next=p->next;
        else L.head=p->next;
        if(p->next != NIL) p->next->last=p->last;

        return p->data;
    }
}

int main(int argc, char *argv[])
{
    Link L; L.head=NIL;
    list x(15);
    INSERT(L,x);
    list y(25);
    INSERT(L,y);
    int dele=DELETE_KEY(L,25);

    cout << L.head->data <<endl;
    cout << dele <<endl;
    cout << "Hello World!" << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值