2012-05-08 31 views
0

這裏是它的工作改善我的鏈表程序

#include <stdio.h> 
#include <stdlib.h> 
struct node { 
    int data; 
    struct node *next, *prev; 
}; 
struct node *root = NULL; 
void push(int); 
void pop(void); 
struct node *create_node(int); 
void travel(void); 
int main() 
{ 
    int i, j, choice, count; 
    printf("enter choice\n"); 
    scanf("%d", &choice); 
    count = 0; 
    while (choice == 1) { 
     printf("enter a data element"); 
     scanf("%d", &j); 
     if (count == 0) { 
      root = (struct node *)malloc(sizeof(struct node)); 
      root->next = NULL; 
      root->data = j; 
     } else 
      push(j); 
     count++; 
     printf("enter choice\n"); 
     scanf("%d", &choice); 
    } 
    printf("the link list is \n"); 
//travel function to be created 
    travel(); 
} 

void push(int data) 
{ 
    struct node *t1; 
    t1 = root; 
    while (t1->next != NULL) { 
     t1 = t1->next; 
    } 
    t1->next = create_node(data); 
} 

void pop() 
{ 
} 

void travel(void) 
{ 
    struct node *t1; 
    t1 = root; 
    while (t1->next != NULL) { 
     printf("%d ", t1->data); 
     t1 = t1->next; 
    } 
    printf("%d ", t1->data); 
} 

struct node *create_node(int data) 
{ 
    struct node *p = (struct node *)malloc(sizeof(struct node)); 
    p->data = data; 
    p->next = NULL; 
    p->prev = NULL; 
    return p; 
} 

上面的程序是完全的工作,我已經使用了一個全局指針根的程序。 我的問題是,如果我不想在這裏使用一個全球性的指針根那怎麼辦我保持 ,列出因爲每次我將不得不返回列表的根在我的推彈出功能 是否有任何其他的方式來實現相同?

回答

2

實現這一目標的最簡單方法是一個指向根節點指針傳遞給每個函數:

void push(struct node **root, int data) { ... } 
void pop(struct node **root) { ... } 
void travel(struct node *root) { ... } 

所以,在你的主要功能可能會聲明一個局部變量來保存根指針:

struct node *root = NULL; 

,然後當你打電話push,例如,你傳遞根poiner地址:

push(&root, data); 

我強烈建議您修復pushtravel函數,以便它們對根指針NULL健壯。這是在你以前的問題中討論過的,你應該聽取建議。

如果你這樣做,那麼你可以得到count爲零和相關的特殊情況代碼擺脫了測試。然後,您可以取代這個:

if (count == 0) { 
    root = (struct node *)malloc(sizeof(struct node)); 
    root->next = NULL; 
    root->data = j; 
} else 
    push(&root, j); 

與此:

push(&root, j); 

開車回家的消息,你的新push應該是這樣的:

void push(struct node **root, int data) 
{ 
    if (*root == NULL) 
     *root = create_node(data); 
    else 
    { 
     struct node *last = *root; 
     while (last->next != NULL) { 
      last = last->next; 
     } 
     last->next = create_node(data); 
    } 
} 

您將需要修改travel還包括對root節點的檢查是NULL。我會把它作爲你的練習。

維護頭部和尾部指針可能是一個更好的方法,因爲它會避免太多的列表遍歷。