我的基礎是附加到結構鏈表的代碼,現在我已經轉向使用結構指標來進行新專案,但我無法讓代碼作業,沒有輸出。當我通過除錯模式運行它時,我發現我附加到鏈表末尾的方法不起作用。
這是我的結構,我使用結構來保存鏈表,因為它比單獨使用頭指標更好。
typedef struct competitor competitor;
typedef struct ll_competitor ll_competitor;
struct competitor {
int data;
competitor *next;
};
struct ll_competitor {
struct competitor *head;
int size;
};
這只是創建一個指向結構的指標,存盤傳遞的資料并回傳它
competitor* make_competitor(int data){
competitor *competitor_ptr;
competitor_ptr = malloc(sizeof(competitor));
if (competitor_ptr != NULL){ // if malloc was successful
competitor_ptr->data = data;
competitor_ptr->next = NULL;
}
return competitor_ptr;
}
這應該將一個專案添加到鏈表的末尾
void insert_tail_competitor(ll_competitor *ll, competitor *insertion){
competitor *temp_pointer;
temp_pointer = ll->head;
while (temp_pointer != NULL){ // while not null aka until the end of this chain
temp_pointer = (temp_pointer)->next;
}
temp_pointer = insertion;
}
這應該遍歷鏈表,輸出資料
void print_all_competitors(ll_competitor *ll){
printf("Print all competitors");
competitor *temp_ptr = ll->head;
int counter = 0;
while (temp_ptr != NULL){
printf("\nCount: %d\n", counter );
printf("data: %d",temp_ptr->data);
temp_ptr = temp_ptr->next;
}
}
為我構建鏈表
ll_competitor *make_competitor_ll(){
ll_competitor *ll = malloc(sizeof *ll); // do a linked list builder later
ll->head=NULL; ll->size=0;
return ll;
}
Main 使用 make_competitor 函式初始化 5 個指向競爭對手的指標,我希望輸出為 1 2 3 4 5
int main() {
ll_competitor *ll = make_competitor_ll();
competitor* c1 = make_competitor(1);
competitor* c2 = make_competitor(2);
competitor* c3 = make_competitor(3);
competitor* c4 = make_competitor(4);
competitor* c5 = make_competitor(5);
insert_tail_competitor(ll,c1);
insert_tail_competitor(ll,c2);
insert_tail_competitor(ll,c3);
insert_tail_competitor(ll,c4);
insert_tail_competitor(ll,c5);
print_all_competitors(ll);
return 0;
}
編輯:為了澄清我的困惑,這是我基于此的代碼
typedef struct node_tag *node_pointer;
typedef struct node_tag{
int data;
node_pointer next;
}node;
void insert_at_tail(node_pointer *pointer_to_head, node_pointer new_node_pointer){
node_pointer *temp_pointer;
temp_pointer = pointer_to_head;
while (*temp_pointer != NULL){
temp_pointer = &(*temp_pointer)->next;
}
new_node_pointer->next = *temp_pointer;
*temp_pointer = new_node_pointer;
}
uj5u.com熱心網友回復:
唯一要做的insert_tail_competitor就是定義一個名為的區域變數temp_pointer,然后多次更改該指標,因此我們不希望該函式對程式中的資料產生任何持久影響。
如果你想在你的鏈表中添加一個條目,你實際上需要修改next一個結構的指標。
也許這會起作用:
void insert_tail_competitor(ll_competitor * ll, competitor * insertion)
{
competitor * c = ll->head;
if (c == NULL)
{
ll->head = insertion;
return;
}
while (c->next != NULL) { c = c->next; }
c->next = insertion;
}
(順便說一句,對于更易于維護的代碼,您可能希望找到某種方法來處理c == NULL與其他情況相同的特殊情況,但現在讓我們保持簡單。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406178.html
標籤:
下一篇:使用偏移量訪問結構成員char*
