我正在研究一个飞行程序,但我无法为该程序添加新路线。这是我的代码,如何解决? 我希望用户输入航班来源、目的地和号码等数据。 如何从用户那里获取数据并存储该信息。感谢大家的帮助:/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
struct flightnode {
char source[20];
char destination[20];
struct flightnode *next;
};
struct flightnode* head = NULL;
struct flightnode* temp = NULL;
struct flightnode* k = NULL;
char source[20];
char destination[20];
/*void addtoend(char x) {
struct node* newtemp = (struct node*)malloc(sizeof(struct flightnode));
newtemp->source = x;
newtemp->next = NULL;
}*/
int main() {
head = (struct flightnode*)malloc(sizeof(struct flightnode));
temp= (struct flightnode*)malloc(sizeof(struct flightnode));
printf("for source: n");
scanf(" %s", &source);
printf("for dest: n");
scanf(" %s",&destination);
strcpy(head->source,source);
strcpy(temp->destination,destination);
printf("source : %sn", head->source);
printf("dest : %s", temp->destination);
return 0;
}
在列表头文件下 #include 使用 adjList.push_back(data(,其中 adjList 是链接列表的名称
首先,不清楚你想要什么newtemp->source = x;
.您不能将单个字符分配给字符数组...我假设它是一个字符串...
无论如何 - 添加到链表末尾的经典方法是:
void addtoend(struct flightnode **p, char* x)
{
// Construct the new node
struct node* newtemp = malloc(sizeof *newtemp);
strcpy(newtemp->source, x);
newtemp->next = NULL;
// Is the list empty?
if (*p == NULL)
{
// yes... so the new node will be the new head
*p = newtemp;
return;
}
// Iterate to last node
struct flightnode *tmp = *p;
while(tmp->next != NULL) tmp = tmp->next;
// Add new node after last node
tmp->next = newtemp;
}
并像这样称呼它:
addtoend(&head, "Hello");
还有一个完整的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct flightnode {
char source[20];
char destination[20];
struct flightnode *next;
};
void addtoend(struct flightnode **p, char* x)
{
// Construct the new node
struct flightnode* newtemp = malloc(sizeof *newtemp);
strcpy(newtemp->source, x);
newtemp->next = NULL;
// Is the list empty?
if (*p == NULL)
{
// yes... so the new node will be the new head
*p = newtemp;
return;
}
// Iterate to last node
struct flightnode *tmp = *p;
while(tmp->next != NULL) tmp = tmp->next;
// Add new node after last node
tmp->next = newtemp;
}
void printList(struct flightnode *p)
{
printf("---- LIST ----n");
while(p)
{
printf("%sn", p->source);
p = p->next;
}
printf("--------------n");
}
int main() {
struct flightnode* head = NULL;
addtoend(&head, "Hello");
printList(head);
addtoend(&head, "world");
printList(head);
addtoend(&head, "have");
printList(head);
addtoend(&head, "a");
printList(head);
addtoend(&head, "nice");
printList(head);
addtoend(&head, "day");
printList(head);
return 0;
}
输出:
---- LIST ----
Hello
--------------
---- LIST ----
Hello
world
--------------
---- LIST ----
Hello
world
have
--------------
---- LIST ----
Hello
world
have
a
--------------
---- LIST ----
Hello
world
have
a
nice
--------------
---- LIST ----
Hello
world
have
a
nice
day
--------------