#include<iostream>
#include<cstring>
#include <set>
#include <map>
#include <ctime>
#include <bitset>
#include <sstream>
#include <algorithm>
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
typedef struct DNode{
int data;
struct DNode *prior,*next;
}DNode,*DLinkList;
void isEmpty(DLinkList &L){
if(L->next==NULL){
cout<<"当前双链表为空"<<endl;
}else{
cout<<"当前双链表非空"<<endl;
}
}
bool InsertNextDNode(DNode *p,DNode *s){
if(p==NULL||s==NULL){
return false;
}
s->next=p->next;
if(p->next!=NULL){
p->next->prior=s;
}
s->prior=p;
p->next=s;
return true;
}
bool DeleteNextNode(DNode *p){
if(p==NULL) return false;
DNode *q=p->next;
if(q==NULL) return false;
p->next=q->next;
if(q->next!=NULL)
q->next->prior=p;
free(q);
return true;
}
void ReadDLinkList(DLinkList &L){
DNode * M= (DNode*) malloc(sizeof(DNode));
M=L;
while(M->next!=NULL){
M=M->next;
cout<<M->data<<"\t";
}
cout<<endl;
}
DLinkList InitDLinkList(DLinkList &L){
L = (DNode *) malloc(sizeof(DNode));
if(L==NULL){
return false;
}
L->prior=NULL;
L->next=NULL;
cout<<"依次输入整形的数据作为双链表的结点数据,并且以-1作为输入结束。"<<endl;
int data;
cin>>data;
DNode * M =(DNode *) malloc(sizeof(DNode));
M=L;
while(-1!=data){
DNode *temp = (DNode *) malloc(sizeof(DNode));
temp->data=data;
InsertNextDNode(M,temp);
M=M->next;
cin>>data;
}
return L;
}
int GetLinkListLength(DLinkList &L){
if(L->next==NULL)
return 0;
int length=0;
DLinkList M=(DNode *) malloc (sizeof(DNode));
M = L;
while(M->next!=NULL){
M = M->next;
length++;
}
return length;
}
void SearchByPosition(DLinkList &L,int x){
int length = GetLinkListLength(L);
if(length==0){
cout<<"当前双链表的长度为0"<<endl;
return ;
}else{
DLinkList M=(DNode *) malloc (sizeof(DNode));
M = L;
int i =0;
while(x>length){
cout<<"\n查找位置超出链表长度,情重新输入。"<<endl;
cin>>x;
if(x<0){
cout<<"\n输入非法,输入的值不能小于0,请重新输入。"<<endl;
cin>>x;
}
}
while(i<x){
M=M->next;
i++;
}
cout<<M->data;
}
return ;
}
void VerifyValue(DLinkList &L,int value){
DLinkList M=(DNode *) malloc (sizeof(DNode));
M = L;
M=M->next;
while(M->data!=value&&M->next!=NULL){
M=M->next;
if(M->data==value){
cout<<"该值在链表中"<<endl;
return ;
}
}
cout<<"该值不在链表中"<<endl;
}
int main()
{
DNode *L;
L = InitDLinkList(L);
ReadDLinkList(L);
isEmpty(L);
cout<<"\n按位查找,请输入要查找的第n个结点的值"<<endl;
int i;
cin>>i;
SearchByPosition(L,i);
cout<<"\n按值查找,请输入要验证的值"<<endl;
int j;
cin>>j;
VerifyValue(L,j);
cout<<"\n对双链表进行删除操作…"<<endl;
while(L->next!=NULL){
DeleteNextNode(L);
}
isEmpty(L);
free(L);
return 0;
}
|