双链表的c++操作实现

#include<iostream>
#include<stdlib.h> 
using namespace std;
typedef struct node
{
int data;
struct node *prior;
struct node *next;
}DNode;


//创建一个带有头结点的双链表


void CreateDLink(DNode *&head) 
{
int x;
DNode *p,*s;
s=(DNode *)malloc(sizeof(DNode));  
if(s==NULL)
{
cout<<"Fail to malloc the head node!"<<endl;
}
s->data = 0;
s->prior = NULL;
s->next = NULL;
head = s;
cout<<"please input the data of the node"<<endl;
cin>>x;
while(x!=0)
{
p = (DNode*)malloc(sizeof(DNode));
if(p==NULL)
{
cout<<"Fail to molloc a new node!"<<endl;
}
s->next = p;
p->prior = s;
p->next = NULL;
p->data = x;
s = p;
cin>>x;
}





void PrintDLink(DNode *head)
{
if(head->next == NULL)
{
cout<<"The List is NULL"<<endl;
return;
}
DNode *p;
p = head->next;
while(p != NULL)
{
cout<<"链表元素:"<<p->data<<" ";
p = p->next;

}
cout<<endl;
}


//求链表长度
int Length(DNode *head)
{
int len = 0;
DNode *p = head->next;
while(p != NULL)
{
len++;
p = p->next;
}
return len;



DNode *Get(DNode *head,int i)
{
int j = 0;
DNode *p = head->next;
while(j<i&&p!=NULL)
{
j++;
p = p->next;
}
if(p!=NULL)
{
return p;
}
else 
return NULL;
}


//在第i个位置插入一个节点
int InsertNode(DNode *head,int x,int i)
{
DNode *s,*p;
s = (DNode*)malloc(sizeof(DNode));
s->data = x;
if(i == 0)
{
s->next = head->next;
if(head->next!=NULL)
head->next->prior = s;
s->prior = head;
head->next = s;
}
else
{
p = Get(head,i-1);
if(p==NULL)
{
return 0;
}
else
{
s->next = p->next;
if(p->next!=NULL)
p->next->prior = s;
s->prior = p;
p->next = s;
}
}
return 1;



void DeleteNode(DNode *head,int index)
{
if(head->next==NULL)
{
cout<<"the list is null";
}
DNode *p,*s;//保存待删除的节点
if(index == 0)
{
s = head->next;
head->next = s->next;
if(s->next!=NULL)
s->next->prior = head;
free(s);
}
else
{
p = Get(head,index-1);
if(p==NULL)
{
cout<<"The node"<<index<<"is not exist"<<endl;

}
else
{
s = p->next;
p->next = s->next;
if(s->next!=NULL)
s->next->prior = p;
free(s);
}
}
}


int main()
{
DNode *head;
CreateDLink(head);
cout<<"链表长度:"<<Length(head)<<endl;
PrintDLink(head);
cout<<"第3个节点的值为:"<<Get(head,3)->data<<endl;
cout<<"输入插入节点的位置及值:"<<endl;  
int value, index;  
        cin>>value>>index;  
        InsertNode(head,value,index);  
        cout<<"插入后的链表为:"<<endl;  
        PrintDLink(head);  
  
       cout<<"请输入要删除的节点位置:"<<endl;  
       cin>>index;  
       DeleteNode(head,index);  
       PrintDLink(head);  
       return 0;  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值