问题描述
- 关于头插入法建立双向链表
-
//还没实现
#include
#include
#include
#define OK 1
typedef int elemtype;
typedef int states;
typedef struct DuLNode{
elemtype data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLinkList;
states create(DuLinkList &L){
DuLinkList p;
L = (DuLinkList)malloc(sizeof(DuLNode));
L->next = NULL;
L->prior = NULL;
printf("please input the length of list:n");
int n;
scanf("%d",&n);
for (int i = n; i > 0; i--){
p = (DuLinkList)malloc(sizeof(DuLNode));
printf("please input data of element No.%dn", i);
scanf("%d", &p->data);
if (L->next = NULL){ L->next = p;
p->prior = L;
p->next = NULL;} else{ p->next = L->next; p->prior = L; L->next->prior = p; L->next = p; } } return OK;
}
void print(DuLinkList L){
DuLinkList p;
p = L->next;
printf("the linklist is like this:n");
while (p){printf("t%d", p->data); p = p->next; } printf("n");
}
void main(){
DuLinkList L;
create(L);
print(L);
system("pause");
}
实在不造哪里不对了。。。求助大神啊感激不尽!!!
解决方案
if (L->next = NULL){ L->next = p;
p->prior = L;
p->next = NULL;
}
else{
p->next = L->next;
p->prior = L;//这里L就没变过,所有新创建的节点,它的prior都是执行L的,肯定错了
L->next->prior = p;
L->next = p; //L没变过,也意味着L-next指向的永远是新节点,根据L只能找到一个节点
}
}
基于你的代码改了一下
#define OK 1
typedef int elemtype;
typedef int states;
typedef struct DuLNode{
elemtype data;
struct DuLNode *prior;
struct DuLNode *next;
}DuLNode,*DuLinkList;
states create(DuLinkList &L){
DuLinkList p;
DuLinkList L1=NULL;
L = (DuLinkList)malloc(sizeof(DuLNode));
L->next = NULL;
L->prior = NULL;
printf("please input the length of list:n");
int n;
scanf("%d",&n);
for (int i = n; i > 0; i--){
p = (DuLinkList)malloc(sizeof(DuLNode));
printf("please input data of element No.%dn", i);
scanf("%d", &p->data);
if(L1!=NULL){
L1->next = p;
p->prior = L1;
p->next = NULL;
L1 = p;
}else{
L = p;
L1 = p;
}
}
return OK;
}
void print(DuLinkList L){
DuLinkList p;
p = L;
printf("the linklist is like this:n");
while (p){
printf("t%d", p->data);
p = p->next;
}
printf("n");
}
void main(){
DuLinkList L;
create(L);
print(L);
system("pause");
}
解决方案二:
http://blog.csdn.net/eric802/article/details/6680244
http://www.nowamagic.net/librarys/veda/detail/1810
http://blog.csdn.net/summersunboy/article/details/6137636
解决方案三:
你能先把代码贴整齐了我再帮你看看吧.
时间: 2024-10-25 22:20:27