实现双向链表的插入删除和查询,并写出测试用例。
#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了,一直在考虑循环链表的头和尾指针为题。。。。。