#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int number;
struct node* next;
}
node;
int main(void){
node* list = NULL;
node *n = malloc(sizeof(node));
if(n==NULL){
return 1;
}
n->number = 2;
n-> next = NULL;
list = n;
n = malloc(sizeof(node));
if(n == NULL){
free(list);
return 1;
}
n->number = 3;
n->next = NULL;
list->next = n;
n = malloc(sizeof(node));
if(n == NULL){
free(list->next);
free(list);
}
n->number = 4;
n->next = NULL;
list->next->next =n;
n = malloc(sizeof(node));
if(n!=NULL){
n->number = 0;
n->next = NULL;
n->next = list;
list = n;
}
for( node* tmp = list; tmp != NULL; tmp->next){
printf("%i\n" , tmp->number);
}
while(list!=NULL){
node*tmp = list->next;
free(list);
list=tmp;
}
}
正在嘗試鏈表。expected when running the code: 0 1 2 3 4 $ //asdoihasidashiofdhiohdfgdiwheifiopioioiophfaifjasklfhafiashfauiosfhwuiohwefuiowhfaslfidasdaskdasjdlaksdjqwfiqpweiojfkldfjsdfklwhefiowefweopfiosfkosid;fjwdfp;fdasiopfjew[0fowejfwepfojmofejmiwrfgj;wdfjewio;fijwefjsdp;jfkl;wjw
uj5u.com熱心網友回復:
實際上你并沒有改變指標
for( node* tmp = list; tmp != NULL; tmp->next){
你需要寫
for( node* tmp = list; tmp != NULL; tmp = tmp->next){
寫出來會更好
for ( const node* tmp = list; tmp != NULL; tmp = tmp->next ){
因為在回圈中串列沒有被改變。
同樣在此代碼段中
if(n!=NULL){
n->number = 0;
n->next = NULL;
n->next = list;
list = n;
}
該宣告
n->next = NULL;
是多余的。
uj5u.com熱心網友回復:
在這個回圈中,tmp->next沒有任何效果,因為你沒有將它分配給任何東西。
for (node* tmp = list; tmp != NULL; tmp->next) {
printf("%i\n", tmp->number);
}
你必須這樣做tmp = tmp->next:
for (node* tmp = list; tmp != NULL; tmp = tmp->next) {
// ^^^^^
printf("%i\n", tmp->number);
}
此外,您不能期望1出現在輸出中,因為您從未創建具有該編號的節點。因此,通過上述更改,程式將輸出:
0
2
3
4
旁注:你的程式充滿了重復,這使得很難找到錯誤,這也讓你更難看到你忘記添加node數字1。如果你把你重復做的事情變成函式,它會更清晰。您還可以使用描述性名稱制作函式,以使整個程式更易于閱讀和維護。
如果您的程式被重寫以使用函式,它可能如下所示 - 然后很明顯,缺少node帶有數字的 。1
#include <stdio.h>
#include <stdlib.h>
typedef struct node node;
struct node {
int number;
node* next;
};
node *create_node(int number, node *next) {
node *nn = malloc(sizeof *nn);
if(!nn) exit(1);
// assign values to the new node:
*nn = (node){.number = number,
.next = next};
return nn;
}
void insert_first(node **list, int number) {
*list = create_node(number, *list);
}
void insert_last(node **list, int number) {
// find the last "next" pointer (the one pointing at NULL):
while(*list) list = &(*list)->next;
// make the pointer pointing at NULL now point at the new node:
*list = create_node(number, NULL);
}
void free_all(node **list) {
for(node *tmp; *list; *list = tmp) {
tmp = (*list)->next;
free(*list);
}
}
void print_all(const node *list) {
for (; list; list = list->next) {
printf("%d\n", list->number);
}
}
int main(void) {
node* list = NULL;
insert_last(&list, 2);
insert_last(&list, 3);
insert_last(&list, 4);
insert_first(&list, 0);
print_all(list);
free_all(&list); // list == NULL after this
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/522532.html
下一篇:如何迭代熊貓中的特定索引?
