双链表的操作

来源:互联网 发布:淘宝只退款不退货教程 编辑:程序博客网 时间:2024/06/11 04:11
#include <iostream>#define NIL 0using 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;}