双链表的情况和单链表类似,只是增加了一个前置而已。
,不多说,直接看代码;
// DoubleLink.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
struct DoubleNode
{
int data;
DoubleNode* pre;
DoubleNode* next;
};
DoubleNode* create_DoubleLink(int a[],int len)
{
DoubleNode* head,*p,*q;
p=new DoubleNode();
p->data=a[0];
head=p;
head->pre=NULL;
for (int i=1;i<len;i++)
{
q=new DoubleNode();
q->data=a[i];
q->pre=p;
p->next=q;
p=q;
}
p->next=NULL;
return head;
}
DoubleNode* deleteTheNode(DoubleNode* head,int num)
{
DoubleNode* p1,*p2;
p1=head;
while (p1->next&&num!=p1->data)
{
p1=p1->next;
}
if (num==p1->data)
{
if (p1==head)//找到的是头节点
{
head=head->next;
head->pre=NULL;
}
else if(p1->next)//不是头结点,也不是尾节点
{
p1->next->pre=p1->pre;
p1->pre->next=p1->next;
}
else
{
p1->pre->next=NULL;
free(p1);
}
}
else
{
cout<<"节点未找到"<<endl;
}
return head;
}
//顺序双向链表的插入
DoubleNode* insert(DoubleNode* head,int num)
{
DoubleNode* p0,*p1;
p1=head;
p0=new DoubleNode();
p0->data=num;
while (p1->next!=NULL&&p1->data<p0->data)
{
p1=p1->next;
}
if (p0->data<=p1->data)
{
//如果p1就是头节点
if (p1==head)
{
p1->pre=p0;
p0->next=p1;
head=p0;
}
else
{
//如果p1就是中间的节点
p1->pre->next=p0;
p0->next=p1;
p0->pre=p1->pre;
p1->pre=p0;
}
}
else
{
//说明比哪个都大
p1->next=p0;
p0->pre=p1;
p0->next=NULL;
}
return head;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[]={1,2,4,7,9};
int len=sizeof(a)/sizeof(int);
DoubleNode* head=create_DoubleLink(a,len);
head=insert(head,-1);
head=insert(head,6);
head=insert(head,10);
head = deleteTheNode(head,4);
system("pause");
return 0;
}