Professional Documents
Culture Documents
xử lý giỏ hàng dùng danh sách liên kết đơn
xử lý giỏ hàng dùng danh sách liên kết đơn
xử lý giỏ hàng dùng danh sách liên kết đơn
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (*head == NULL) {
*head = newItem;
}
else {
Item* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newItem;
}
}
count++;
addItem(head, ID, quantity, insertDate, price);
}
printf("Total: %d\n", count);
}
/////////////////////////////////////////////////////////////////////////////////
// PHẦN CODE LÀM CỦA SINH VIÊN
//////////////////////////////////////////////////
// Hàm tính tổng tiền sản phẩm trong giỏ hàng
double checkCartTotalPrice(Item* head) {
// SINH VIÊN CODE TIẾP VÀO ĐÂY
if (head == NULL) return 0;
double sum = 0;
Item *temp = head;
while (temp != NULL) {
sum += temp->price * temp->quantity;
temp = temp->next;
}
return sum;
}
// Hàm để thêm một sản phẩm vào giỏ hàng, nếu đã có thì tăng số
// lượng lên, nếu chưa có thì thêm vào cuối danh sách
// các thông tin được truyền như tham số hàm, ý nghĩa các trường
// giống như tên trường
void addNewItem(Item** head, char ID[], int quantity, char insertDate[], double
price) {
if ((*head) == NULL) addItem(head, ID, quantity, insertDate, price);
else {
Item *temp = findanItemByID((*head), ID);
if (temp == NULL) addItem(head, ID, quantity, insertDate, price);
else temp->quantity += quantity;
}
}
///////////////////////////////////////////////////
// HẾT PHẦN LÀM CỦA SINH VIÊN
////////////////////////////////////////////////////////////////////////////////
if (strcmp(ID, "-1") == 0) {
break;
}
anItem = findanItemByID(head, ID);
if (anItem == NULL) printf("Item NOT FOUND\n");
else printf("Item's already added at %s\n", anItem->insertDate);
}
}
int main() {
Item* cartList = NULL;
char nextCommand[100];
while (1)
{
fgets(nextCommand, sizeof(nextCommand), stdin);
nextCommand[strcspn(nextCommand, "\r\n")] = 0;
if (nextCommand[0] != '?') break;
if (strcmp(&nextCommand[2], "readCart") == 0)
readItemList(&cartList);
else if (strcmp(&nextCommand[2], "findItemsByID") == 0)
findItemsByID(cartList);
else if (strcmp(&nextCommand[2], "reduceItemQuantityByIDs") == 0)
reduceItemQuantityByIDs(&cartList);
else if (strcmp(&nextCommand[2], "addNewItems") == 0)
addNewItems(&cartList);
else if (strcmp(&nextCommand[2], "checkCartTotalPrice") == 0)
printf("Total price: %.2lf\n", checkCartTotalPrice(cartList));
}
return 0;
}