2 sinat 27945027 sinat_27945027 于 2015.05.30 22:17 提问

关于头插入法建立双向链表

//还没实现
#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.%d\n", 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");
}
实在不造哪里不对了。。。求助大神啊感激不尽!!!




3个回答

danielinbiti
danielinbiti   Ds   Rxr 2015.05.30 22:51
已采纳
 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.%d\n", 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");
}
sinat_27945027
sinat_27945027 我知道哪里不对了。。。L->next = NULL 这个等号不对。。。等号是赋值啊赋值啊啊啊啊啊。。。但还是特别感谢你!
2 年多之前 回复
sinat_27945027
sinat_27945027 谢谢你,但这种是不带头结点的双向链表,带有头结点的又应该怎么办呢?
2 年多之前 回复
caozhy
caozhy   Ds   Rxr 2015.05.30 22:23
USTCdingding
USTCdingding   2015.05.30 22:37

你能先把代码贴整齐了我再帮你看看吧.

sinat_27945027
sinat_27945027 我下次一定注意。。。抱歉。。。
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片