2015-04-02 62 views
0

我有一個叫員工在我的程序,定義如下結構:用C動態創建一個單向鏈表

struct employee { 
int id; 
int age; 
struct *employee next; 
}; 

我怎麼會拿在來自用戶的輸入,創建自己的輸入結構,和用指針創建一個單鏈表?我有很多問題想清楚如何動態地做到這一點。在Java中,這很容易通過構造函數完成,但是如何在C中執行此操作?

編輯:假設輸入只是兩個整數(id和年齡)。

+0

我寫了一個博客帖子描述的實現鏈表的http://cyberlingo.blogspot.in/2014/11/linked-lists.html – 2015-04-02 15:21:50

+0

@karma_geek這是一個有點我需要做的事情變得複雜。我是C新手,所以這對我來說仍然頗具挑戰性。 – Richard 2015-04-02 15:25:19

+0

好吧,首先你需要了解動態分配的基礎知識 - 如何使用malloc,free等。另外,你必須知道指針是如何工作的。您的問題非常廣泛,您遇到的任何特定問題? – 2015-04-02 15:27:27

回答

1

這是如何創建一個新的employee結構。您正在使用malloc函數動態分配內存。

struct employee *new_employee = (struct employee*)malloc(sizeof(struct employee)); 

現在,我們需要將數據填充到這個新創建的employee領域:

new_employee -> id = input_id; 
new_employee -> age = input_age; 

對於next指針,它通常給出NULL值。這是爲了防止next指針指向任何任意的內存位置。

new_employee -> next = NULL; 

最後,我們要link的清單。要做到這一點,你必須將以前員工字段的next指針指向當前員工字段(例如:如您在註釋中提到的,第一個(9,3)具有指向第二個字段(3,2)的下一個指針) )

由於它是單向鏈表,我們不能回溯。所以,有兩種方法可以訪問前一個字段。

首先是維護一個指向鏈接列表最後一個字段的指針。

其次是遍歷整個列表直到結束,當到達最後一個元素時,更改它的next指針。

實現第二個方法:

node *temp = *start; 
    if(temp!=NULL) 
    { 
      while(temp -> next) 
       temp = temp -> next; 
      temp -> next = new_employee; 
    } 

希望它能幫助!

1

注意don't give me fish teach me how to fish

這是一個例子:

struct node { 
int value; 
struct *node next; 
}; 

如何動態地創建新的節點指針?

node* aux = (node*) malloc(sizeof(node)); 

如何獲得用戶輸入(安全)?

char line[256]; 
int i; 
if (fgets(line, sizeof(line), stdin)) { 
    if (1 == sscanf(line, "%d", &i)) { 
     /* i can be safely used */ 
    } 
} 

如何創建一個鏈表的頭?

/* This will be the unchanging first node */ 
struct node *root;  
/* Now root points to a node struct */ 
root = (struct node *) malloc(sizeof(struct node)); 
/* The node root points to has its next pointer equal to a null pointer 
    set */ 
root->next = 0; 
/* By using the -> operator, you can modify what the node, 
    a pointer, (root in this case) points to. */ 
root->value = 5; 

如何將新節點添加到鏈接列表?

/* This won't change, or we would lose the list in memory */ 
    struct node *root;  
    /* This will point to each node as it traverses the list */ 
    struct node *conductor; 

    root = malloc(sizeof(struct node)); 
    root->next = 0; 
    root->value = 12; 
    conductor = root; 
    if (conductor != 0) { 
     while (conductor->next != 0) 
     { 
      conductor = conductor->next; 
     } 
    } 
    /* Creates a node at the end of the list */ 
    conductor->next = malloc(sizeof(struct node)); 

    conductor = conductor->next; 

    if (conductor == 0) 
    { 
     printf("Out of memory"); 
     return 0; 
    } 
    /* initialize the new memory */ 
    conductor->next = 0;   
    conductor->value = 42; 

現在,你必須能夠很容易地解決這個問題。

快樂編碼:d