//带头节点双链表
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef int type;
typedef struct DNode{
type data;
struct DNode *prior;
struct DNode *next;
} DNode ,*DLinkNode;
//初始化头节点
void init(DLinkNode &head){
head=(DLinkNode)malloc(sizeof(DNode));
head->prior=NULL;
head->next=NULL;
}
//头插法
DLinkNode createR(){
DLinkNode head,s;
init(head);
type x;
cin>>x;
while(x!=-1){
s=(DLinkNode)malloc(sizeof(DNode));
s->data=x;
s->next=head->next;
s->prior=head;
head->next=s;
cin>>x;
}
return head;
}
//尾插法
DLinkNode createF(){
DLinkNode head,s,p;
init(head);
p=head; //一点要初始化之后在赋值
type x;
cin>>x;
while(x!=-1){
s=(DLinkNode)malloc(sizeof(DNode));
s->data=x;
s->next=p->next;
p->next=s;
s->prior=p;
p=s;
cin>>x;
}
return head;
}
//判断链表是否为空
int isEmpty(DLinkNode head){
return head->next==NULL;
}
//返回链表长度
int length(DLinkNode head){
DLinkNode p=head->next;
int len=0;
while(p){
len++;
p=p->next;
}
return len;
}
//销毁链表
void destroy(DLinkNode &head){
DLinkNode p;
while(head){
p=head->next;
free(head);
head=p;
}
}
//在指定位置插入元素
int insertElem(DLinkNode head,int p,type x){
if(p<0||p>length(head)) return -1;
DLinkNode q=head->next;
int i=0;
while(q&&i!=p-1){
q=q->next;
i++;
}
DLinkNode s=(DLinkNode)malloc(sizeof(DNode));
s->data=x;
s->next=q->next;
s->prior=q;
q->next=s;
return 1;
}
//删除指定位置的元素
int deleteElem_p(DLinkNode head,int p){
if(isEmpty(head)||p<0||p>=length(head)) return -1;
DLinkNode q=head->next;
int i=0;
while(q->next&&i!=p){
q=q->next;
i++;
}
q->prior->next=q->next;
free(q);
return 1;
}
//删除指定链表中的指定值
int deleteElem(DLinkNode head,int x){
if(isEmpty(head)) return -1;
DLinkNode q=head->next;
DLinkNode l,p=head;
while(q->next){
if(q->data==x){
l=q;
p->next=l->next;
l->next->prior=p;
q=p->next;
free(l);
}
else{
p=p->next;
q=q->next;
}
}
if(q->data==x){ //最后一个结点是要删除的结点
p->next=NULL;
}
return 1;
}
//查找指定元素第一次出现的位置
int findElem(DLinkNode head,int x){
if(isEmpty(head)) return -1;
DLinkNode q=head->next;
int i=0;
while(q&&q->data!=x) i++,q=q->next;
if(q==NULL) return -1;
return i;
}
//返回指定位置的元素
type findElem_p(DLinkNode head,int p){
if(isEmpty(head)||p<0||p>=length(head)) return -1;
DLinkNode q=head->next;
int i=0;
while(q&&i!=p) i++,q=q->next;
if(q==NULL) return -1;
return q->data;
}
//打印链表
void print(DLinkNode head){
if(isEmpty(head)) return ;
DLinkNode p=head->next;
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main(){
//DLinkNode head=createR();
//print(head);
DLinkNode head=createF();
print(head);
//insertElem(head,3,99);
print(head);
//deleteElem_p(head,3);
print(head);
//deleteElem(head,2);
//print(head);
cout<<findElem(head,2)<<endl;
cout<<findElem_p(head,4)<<endl;
cout<<length(head)<<endl;
destroy(head);
print(head);
return 0;
}
基础数据结构——双链表
猜你喜欢
转载自blog.csdn.net/Unknow_if/article/details/117461244
今日推荐
周排行