我不知道你想要什麼來實現這個功能,因爲在這裏你不會在任何輸入掃描:
char obtain_next_char(){
if (n<100) {
return 'a';
} else {
return 0;
}
}
也許你需要這個:
char obtain_next_char()
{
char c;
scanf(" %c",&c); //scanning input
if (n<100) //if number of links < 100 then, return character
{
return c;
}
else //else return '0' (ascii character)
{
return '0';
}
}
,但它在列表的最後導致一個空節點
原因:
的問題是,被在年底創建了一個新的節點,而循環
while ((c=obtain_next_char()) != 0)
{
curr->val = c;
curr->next = malloc(sizeof(node)); //new node at end of each iteration
curr = curr->next;
}
所以,當你結束輸入,最後一個空節點仍然
溶液:(不與代碼的循環外第一節點)
爲了避免這個問題,嘗試在每個迭代
while ((c=obtain_next_char()) != '0')
{
if(n != 0) //to avoid again creating for head node
{
curr->next = malloc(sizeof(node));
curr = curr->next;
}
curr->val = c;
n++; //increasing number of links
}
- 這種方式,開始創建節點,您可以避免在每次迭代結束時創建額外的空節點。
我不想建立與代碼的第一個節點的循環
while ((c=obtain_next_char()) != '0')
{
if(n != 0) //any other node
{
curr->next = malloc(sizeof(node));
curr = curr->next;
}
else //for head node
{
start = malloc(sizeof(node));
curr = start;
}
curr->val = c;
n++; //increasing number of links made
}
乾脆把你的外碼將是:
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s {
char val;
struct node_s *next;
} node;
int n;
char obtain_next_char()
{
char c;
scanf(" %c",&c);
if (n<100)
{
return c;
}
else
{
return '0';
}
}
int main() {
char c;
node *start=NULL, *curr=NULL;
n = 0;
while ((c=obtain_next_char()) != '0')
{
if(n != 0) //any other node
{
curr->next = malloc(sizeof(node));
curr = curr->next;
}
else //for head node
{
start = malloc(sizeof(node));
curr = start;
}
curr->val = c;
n++;
}
curr->next = NULL;
printf("chain made, %d links\n", n);
curr = start;
while (curr != NULL) {
printf(">>>%c<<<\n",curr->val);
curr=curr->next;
}
}
輸入:
1 2 3 4 5 0
輸出:
chain made, 5 links
>>>1<<<
>>>2<<<
>>>3<<<
>>>4<<<
>>>5<<<
考慮要求這對代碼審查。 – Martin