sinat_27945027
2015-05-30 14:17
采纳率: 100%
浏览 3.0k
已采纳

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

//还没实现
#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 2015-05-30 14: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");
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • threenewbee 2015-05-30 14:23
    评论
    解决 无用
    打赏 举报
  • USTCdingding 2015-05-30 14:37

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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题