2016-05-14 64 views
-1

我完成了爲循環鏈表創建函數。但是,構建和編譯後,我認爲pushFront和insertAfter函數不起作用。因爲當我運行printList函數時,即使我通過pushFront Function推送了另一個節點,它也只打印出一個節點。我的循環鏈表不工作

#include<stdio.h> 
#include<limits.h> 
typedef struct dnode_elm * dnode; 
typedef struct dnode_elm { 
    int item; 
    dnode next, prev; 
}; 

dnode createList(void); 
int isEmpty(dnode h); 
dnode insertAfter(dnode a, int value); 
dnode pushFront(dnode h, int item); 
void printList(dnode h); 

int main(void){ 
int e, ea, eb; 
char cmd[20]; 
dnode h,a,b,x; 
h = createList(); 
while(1){ 
    fflush(stdout); 
    scanf("%s", cmd); 
    if(strcmp(cmd, "pushf")==0) { // pushFront 
     printf("넣을 값을 입력하시오.\n"); 
     fflush(stdout); 
     scanf("%d", &e); 
     pushFront(h,e); 
     printList(h); 
    } else if(strcmp(cmd, "popf")==0) { // popFront 
     popFront(h); 
     printList(h); 
    } else if(strcmp(cmd, "insa")==0) { // insertAfter 
     printf("노드 a의 오른쪽에 새로운 노드 b를 삽입한다.\n"); 
     printf("찾을려는 a->e 와 입력할 b->e의 값을 차례로 입력:"); 
     fflush(stdout); 
     scanf("%d %d", &ea, &eb); 
     if(a = findNext(h, h->next, ea)){ 
      if(a != h) insertAfter(a, eb); 
     } 
     else 
      printf("찾으려는 값이 없습니다. \n"); 
     printList(h); 
    }else if(strcmp(cmd, "print")==0) { // print 
     printList(h); 
    } 
    else if(strcmp(cmd, "exit")==0) //exit 
     break; 
    else 
     printf("다시 입력하시오\n"); 
} 
return 0; 
} 

dnode createList(void){ 
dnode D=(dnode)malloc(sizeof(struct dnode_elm)); 
D->item=INT_MAX; 
D->prev=D->next=D; 
return D; 
} 
int isEmpty(dnode h){ 
if(h->next==h){ 
     return 0; 
} 
return 1; 
} 
dnode insertAfter(dnode a, int value){ 
dnode v=(dnode)malloc(sizeof(struct dnode_elm)); 
v->item=value; 
a->next=v; 
v->prev=a; 
v->next=a->next; 
a->next->prev=v; 
return v; 
} 
dnode pushFront(dnode h, int item){ 
    return insertAfter(h,item); 
} 
void printList(dnode h){ 
while(isEmpty(h)==1){ 
     printf("%d --> ",h->item); 
     h=h->next; 
    } 
} 
+1

[**不要強制轉換malloc的返回值**。您錯過了''。](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –

+0

另外,編譯時啓用了**警告並將它們設置爲錯誤例如**'gcc -Wall -Werror'。 –

+0

也請舉一個簡單的例子,添加顯示問題的實際函數調用,現在我們只需要瞭解韓語,並猜測您輸入什麼來重現問題。 –

回答

2

您的插入邏輯錯誤。

a->next=v; 
v->prev=a; 
v->next=a->next; 
a->next->prev=v; 

這個代碼序列後,v->next等於v,這可能不是你想要的。

要解決此問題,您應該首先指定v的指針,然後修復v左右的節點。

v->prev = a; 
v->next = a->next; 
v->next->prev = v; 
v->prev->next = v; 

舉例說明:


enter image description here插入va


enter image description herev->nextv->prev


enter image description here套裝v->next->prevv->prev->next


如果你有雙指針引用邏輯不舒服,請考慮以下等效代碼:

node_to_be_before_v = a; 
node_to_be_after_v = a->next; 
v->prev = node_to_be_before_v; 
v->next = node_to_be_after_v; 
node_to_be_after_v->prev = v; 
node_to_be_before_v->next = v; 
+0

@jxhwhy v-> next-> prev = v; v-> prev-> next = v; –

+0

我不明白... –

+0

@JoJay將下一個和前一個節點設置爲「v」。 (人們可以在'v-> prev'中使用'a',但是這樣寫就更明顯了)。 –