程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 數據結構-關於頭插入法建立雙向鏈表

數據結構-關於頭插入法建立雙向鏈表

編輯:編程綜合問答
關於頭插入法建立雙向鏈表

//還沒實現
#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");
}
實在不造哪裡不對了。。。求助大神啊感激不盡!!!




最佳回答:


 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
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved