#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;
}
双链表的操作
最新推荐文章于 2022-08-05 10:13:06 发布