双向链表的创建、结点的插入、删除与打印

(1)双向链表的创建与单向链表是类似的。其核心也是结点的内存申请以及结点间前后趋关系。

创建如下双链表:


using namespace std;
typedef int type;
typedef struct  node
{
type data;
struct node *pre;
struct node *next;
}Node,*pNode;
//创建双向链表
pNode CreateDoubleList(type *val,int n)
{
pNode head,temp;
head=(pNode)malloc(sizeof(Node));
if(NULL==head)
{
printf("申请头结点内存失败!");
     return NULL;
}

head->pre=NULL;
head->next=NULL;

temp=head;
for(int i=0;i<n;i++)
{
 pNode newNode=(pNode)malloc(sizeof(Node));
 if(NULL==newNode)
 {
   printf("申请新结点内存失败!");
return NULL;
 }
 newNode->data=val[i];
 temp->next=newNode;
 newNode->pre=temp;
 newNode->next=NULL;
 temp=newNode;
}
 return head;
}
//打印双向链表
void printDoubleList(pNode head)
{
if(NULL==head->next)
printf("链表为空!");

pNode temp=head->next;
while(NULL!=temp)
{
printf("%3d",temp->data);
temp=temp->next;
}
printf("\n");
}


运行结果为


(2)向双向链表中插入一个结点。分为所插入结点号是否是为尾结点,应分类写出相关代码。

本文中,在第5结点后插入数据为31的结点,代码如下:


//双链表中插入一个结点
pNode InsertNode(pNode head,int num,type data)
{
pNode temp,p;
int m=ListLength(head); //双链表长度
temp=head;
p=(pNode)malloc(sizeof(Node));
if(NULL==p)
{
printf("申请内存失败!");
return NULL;
}
p->data=data;
if(num==m)
{
 temp=temp->next;
 while(NULL!=temp->next)
 {
    temp=temp->next;
 }


 p->next=NULL;
 temp->next=p;
 p->pre=temp;


 return head;
}
else if((num>0)&&(num<m))
{
 while(num)  //查找到要插入结点的位置
 {
 temp=temp->next;
 num--;
 }
 p->next=temp->next;
 temp->next->pre=p;


 temp->next=p;
 p->pre=temp;


 return head;
}
else
{
 return NULL;
}
}


运行结果为:


(3)删除一个结点  找到删除结点的前一结点,并对前后关系进行处理、

代码如下:

//双链表中输出一个结点 
pNode DeleteNode(pNode head, int num)
{
pNode temp =head;
  int m=ListLength(head); //双链表长度


  if((num>0)&&(num<=m))
  {
     while(num>1)  //找到要删除结点的前一结点
{
temp=temp->next;
num--;
}


temp->next=temp->next->next;
temp->next->next->pre=temp;


return head;
  }
  else
  {
    printf("结点号越界!");
return NULL;
  }

}
int _tmain(int argc, _TCHAR* argv[])
{
type a[6]={11,13,14,15,17,19};


pNode head=CreateDoubleList(a,6);
printDoubleList(head);

pNode p=InsertNode(head,5,31);
printDoubleList(p);
pNode tp=DeleteNode(p,5);
if(NULL!=tp)
{
printf("删除结点成功!\n");
printDoubleList(tp);
}
else
  printf("删除结点失败!");

return 0;
}


运行结果为



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值