双向链表的相关操作
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
typedef struct Node
{
int x;
Node *next;
Node *pre;
}Node,*Lnode;
void creat(Node& node,int n,int *a)
{
Lnode p=&node,q;
for(int i=n-1;i>=0;i--)
{
q= new Node;
q->next=NULL;
q->pre=NULL;
q->x=a[i];
p->next->pre=q;
q->next=p->next;
q->pre=p;
p->next=q;
}
}
bool Del(Node& node,int num)
{
Lnode p=node.next,q=&node;
for(p;p!=q;p=p->next)
{
if(p->x==num) // 找到这个元素num了
{
q=p;
p->pre->next=p->next;
p->next->pre=p->pre;
free(q);
return true;
}
}
return false;
}
void Prin(Node& node)
{
Lnode p=node.next,q=&node;
for(p;p!=q;p=p->next)
cout<<p->x<<endl;
cout<<"end"<<endl;
}
bool Add(Node& node,int i,int num)
{ // 在第i个位置插入元素num(默认从head开始)
Lnode p=node.next,q=&node;
int k=1;
for(;k<i;p=p->next,k++) ;
// 现在就相当于在q和p中插入一个元素
Lnode r=new Node;
r->x=num;
r->next=r->pre=NULL;
p->pre->next=r;
r->pre=p->pre;
r->next=p;
p->pre=r;
return true;
}
void SupPrin(Node& node ,int i) // 为了验证循环列表的正确性,从第i个节点开始输出
{
Lnode p=node.next,q;
int k=1;
for(;k<i;)
{
p=p->next;
k++;
}
// 现在是从p开始打印了
// 需要注意到一点是,我这个node类型,head是空的,在输出结果的时候需要跳过head.x
q=p;
for(p;p!=&node;p=p->next)
cout<<p->x<<endl;
p=node.next;
for(;p!=q;p=p->next)
cout<<p->x<<endl;
cout<<endl;
}
int main()
{
Node head;
head.next=&head;
head.pre=&head;
int a[5]={2,3,5,1,78};
creat(head,5,a);
Prin(head);
bool t1=Del(head,5);
cout<<t1<<endl;
Prin(head);
cout<<endl<<endl;
SupPrin(head,2);
cout<<endl<<endl;
Add(head,2,45);
Add(head,2,35);
Add(head,2,15);
Add(head,2,65);
Prin(head);
return 0;
}