程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> c語言-為什麼第二次調用show_all還能打印出數據,指針不是已經到了鏈表的最後了嗎

c語言-為什麼第二次調用show_all還能打印出數據,指針不是已經到了鏈表的最後了嗎

編輯:編程解疑
為什麼第二次調用show_all還能打印出數據,指針不是已經到了鏈表的最後了嗎

#include
#include
struct student
{
int num;
float score;
struct student pnext;
};
typedef struct student st;
void add(st **phead, int inum, float iscore)
{
if (*phead == NULL)
{
st *newnode = (st
)malloc(sizeof(st));
newnode->num = inum;
newnode->score = iscore;
newnode->pnext = NULL;
phead = newnode;
}
else
{
st *p = *phead;
while (p->pnext != NULL)
{
p = p->pnext;
}
st *newnode = (st
)malloc(sizeof(st));
newnode->num = inum;
newnode->score = iscore;
newnode->pnext = NULL;
p->pnext = newnode;
}
}
void show_all(st*head)
{
while (head != NULL)
{
printf("%d,%f\n", head->num, head->score);
head = head->pnext;
}
}
void main()
{
st *head=NULL;
add(&head, 1, 20);
add(&head, 2, 30);
add(&head, 3, 40);
add(&head, 4, 50);
add(&head, 5, 60);
show_all(head);
printf("\n");
show_all(head);
system("pause");
}

最佳回答:


有幾個地方少了*

 #include<iostream>
using namespace std;
struct student
{
    int num;
    float score;
    struct student *pnext;
};
typedef struct student st;
void add(st **phead, int inum, float iscore)
{
    if (*phead == NULL)
    {
        st *newnode = (st*)malloc(sizeof(st));
        newnode->num = inum;
        newnode->score = iscore;
        newnode->pnext = NULL;
        *phead = newnode;
    }
    else
    {
        st *p = *phead;
        while (p->pnext != NULL)
        {
            p = p->pnext;
        }
        st *newnode = (st*)malloc(sizeof(st));
        newnode->num = inum;
        newnode->score = iscore;
        newnode->pnext = NULL;
        p->pnext = newnode;
    }
}
void show_all(st*head)
{
    while (head != NULL)
    {
        printf("%d,%f\n", head->num, head->score);
        head = head->pnext;
    }
}
void main()
{
    st *head=NULL;
    add(&head, 1, 20);
    add(&head, 2, 30);
    add(&head, 3, 40);
    add(&head, 4, 50);
    add(&head, 5, 60);
    show_all(head);
    printf("\n");
    show_all(head);
    system("pause");
}

圖片說明

qq423399099
qq_32742637
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved