[英]Inputting Values in the members of structure through linked list
我在 C 工作。 在這里,我有一個結構節點,其中包含數據成員乘客和車站。 我有一個 function 輸入乘客號碼並從用戶那里停止名稱。
struct Node
{
int stopNo;
int passenger;
char station[50];
struct node* next;
};
我有一個 function,它將輸入作為車站名稱和乘客編號,並自動將 stopNo 增加 1。
我正在嘗試使用鏈接列表來存儲電台。
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int stopNo;
int passenger;
char station[50];
struct node* next;
};
void takeInput(struct Node* head)
{
head->stopNo = head->stopNo +1;
printf("Station Name");
scanf(" %[^\n]s",head->station);
printf("New Passengers ");
scanf("%d",&head->passenger);
}
void printStops(struct Node* head)
{
for(int i=0;i<=head->stopNo;i++)
{
printf("Stop %d. %s with %d passenger",head->stopNo,head->station,head->passenger);
}
}
int main()
{ int n;
struct Node* head = NULL;
struct Node* second = NULL;
//Memory Allocation into heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
while(1){
//Menu
printf("1.Log Stops\n");
printf("2.Print Stop");
printf("3.Exit");
scanf("%d",&n);
switch(n){
case 1:
takeInput(struct Node*);
break;
case 2:
printStops(struct Node*);
break;
case 3:
exit(0);
default:
printf("Enter the numbers from 1 to 2");
}
}
}
我很困惑通過 function 作為參數傳遞什么。
您誤用了鏈表概念。
原理是在開頭(更簡單)或結尾(稍微復雜一點)動態添加新節點。 在這里,由於您已經有一個 function 專用於提供列表,您可以在那里分配節點。 一種可能的方法是傳遞當前磁頭的地址,讓function改變它。 但是你必須定義一個標記值來告訴 function 你不想輸入更多的節點。
在下面的代碼中, "STOP"
是那個哨兵:
void takeInput(struct Node **head)
{
int stopNo = 0;
for (;;) {
struct Node *node = malloc(sizeof (*node));
node->stopNo = stopNo++;
node->next = *head;
printf("Station Name");
scanf(" %[^\n]",node->station);
if (strcmp(node->station, "STOP") == 0) { // no more station
free(node);
break;
}
printf("New Passengers ");
scanf("%d",&node->passenger);
*head = node;
}
}
這樣,您可以迭代列表以打印其內容:
void printStops(struct Node* head)
{
while (head != NULL)
{
printf("Stop %d. %s with %d passenger\n",head->stopNo,head->station,head->passenger);
head = head->next;
}
}
最后,你主要會變成:
int main()
{ int n;
struct Node* head = NULL;
while(1){
//Menu
printf("1.Log Stops\n");
printf("2.Print Stop\n");
printf("3.Exit\n");
scanf("%d",&n);
switch(n){
case 1:
takeInput(&head);
break;
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.