[英]How do I go back and edit data in a node in a linked list when my data has multiple elements?
這就是我的鏈接列表的設置方式。 本質上,我正在閱讀客戶和他們訪問過的餐廳的數據。 數據是隨機排列的,但是當我遇到同一個客戶時,我需要返回 go 並編輯為他們創建的節點並將值添加到 timesVisited。 我該怎么做,我應該更改鏈接列表的設置嗎? 我沒有使用文件。
typedef struct customers {
char customerId[CUSTOMER_ID_LENGTH];
int timesVisited[MAX_RESTAURANT_REC];
} data_t;
typedef struct node node_t;
struct node {
data_t *data;
node_t *next;
};
typedef struct {
node_t *head;
node_t *foot;
} list_t;
您應該檢查新條目 customerId 是否已經存在於列表中,在每個節點上一個一個地檢查,您可以使用字符串比較 function,下面是簡短的工作示例,但首先讓我解釋一些代碼片段:
在typedef struct customer
中,不應嵌套指向結構的指針,而是在結構內部聲明它。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CUSTOMER_ID_LENGTH 80
char clients_id[][CUSTOMER_ID_LENGTH] =
{
"AA01",
"AA02",
};
typedef struct customer
{
char customerId[CUSTOMER_ID_LENGTH];
int timesVisited;
struct customer *next; // you should avoid nested structs
}customer_t;
列表 function 通常從頭到尾,由於NULL
指針,您的代碼應該永遠記住頭並識別尾部。
void print_customers(customer_t *head)
{
customer_t * current = head;
while (current != NULL)
{
printf("%s\n", current->customerId);
current = current->next;
}
}
下面的代碼沒有使用循環,它只有兩個節點,但您很快就會明白。
int main()
{
customer_t *head = NULL;
head = (customer_t *) malloc(sizeof(customer_t));
strcpy(head->customerId, clients_id[0]);
head->timesVisited = 1;
head->next = NULL;
head->next = (customer_t *) malloc(sizeof(customer_t));
strcpy(head->next->customerId, clients_id[1]);
head->timesVisited = 1;
head->next->next = NULL;
print_customers(head);
// Change customer entry string and see what happens
char customer_entry[CUSTOMER_ID_LENGTH] = "AA02";
if((strcmp(head->customerId, customer_entry) == 0)|| (strcmp(head->next->customerId, customer_entry) == 0))
{
printf("\nCustomer alredy in list");
}
else
{
printf("\nCustomer is not in the list, just add");
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.