这是一个双向链表的简单操作,为什么不能插入元素 ??
//双向链表的建立、插入……
#include<iostream>
using namespace std;
typedef char Elem;
typedef struct DLNode{
Elem data;
struct DLNode *prior;
struct DLNode *next;
}DLNode,*DListLink;//声明一个双向链表结构
void InitList_L(DListLink &L)//初始化链表
{
L = new DLNode;
L->next = NULL;
L->prior = NULL;
}
int LengthList_L(DListLink &L)//计算链表的长度
{
DLNode *p;
p = L->next;
int Length(0);
while(p)
{
Length++;
p = p->next;
}
return Length;
}
void CreatList_L(DListLink &L,int n)//创建一个双向链表
{
InitList_L(L);
DLNode *p;
cout<<"输入元素:\n";
for(int i(0);i<n;i++)
{
p = new DLNode;
cin>>p->data;
p = p->next;
}
}
DLNode* GetElemP(DListLink &L,int i)//找到指向第i个元素的指针
{
int count(1);
DLNode *p=L->next;
while(p&&count<i)
{
count++;
p = p->next;
}
return p;
}
void InsertElem_L(DListLink &L,int i,Elem x)//在第三个元素之前插入x
{
DLNode *p;
p = GetElemP(L,i);
DLNode *s = new DLNode;
s->data = x;
s->prior = p->prior;
s->next = p;
p->prior->next = s;
p->prior = s;
}
void Display(DListLink L)
{
DLNode *p = L;
while(p)
{
cout<<p->data<<' ';
p = p->next;
}
}
int main()
{
DListLink L;
CreatList_L(L,6);
cout<<endl;
InsertElem_L(L,3,'g');
Display(L);
cout<<endl;
return 0;
} 链表 C++ 指针 双向链表的插入 内存
[解决办法]
首先帮忙你把代码格式化下吧:
//双向链表的建立、插入……
#include<iostream>
using namespace std;
typedef char Elem;
typedef struct DLNode
{
Elem data;
struct DLNode *prior;
struct DLNode *next;
} DLNode,*DListLink; //声明一个双向链表结构
void InitList_L(DListLink &L)//初始化链表
{
L = new DLNode;
L->next = NULL;
L->prior = NULL;
}
int LengthList_L(DListLink &L)//计算链表的长度
{
DLNode *p;
p = L->next;
int Length(0);
while(p)
{
Length++;
p = p->next;
}
return Length;
}
void CreatList_L(DListLink &L,int n)//创建一个双向链表
{
InitList_L(L);
DLNode *p, *pre = NULL;
cout<<"输入元素:\n";
for(int i(0); i<n; i++)
{
p = new DLNode;
if(!L->next){
L->next = p;
p->prior = L;
}else{
pre->next = p;
p->prior = pre;
}
pre = p;
cin>>p->data;
}
}
DLNode* GetElemP(DListLink &L,int i)//找到指向第i个元素的指针
{
int count(1);
DLNode *p=L->next;
while(p&&count<i)
{
count++;
p = p->next;
}
return p;
}
void InsertElem_L(DListLink &L,int i,Elem x)//在第三个元素之前插入x
{
DLNode *p;
p = GetElemP(L,i);
DLNode *s = new DLNode;
s->data = x;
s->prior = p->prior;
s->next = p;
p->prior->next = s;
p->prior = s;
}
void Display(DListLink L)
{
DLNode *p = L;
while(p)
{
cout<<p->data<<' ';
p = p->next;
}
}
int main()
{
DListLink L;
CreatList_L(L,6);
cout<<endl;
InsertElem_L(L,3,'g');
Display(L);
cout<<endl;
return 0;
}
