C++:如何按过期日期的月份对链表数据排序并展示?
按过期日期月份对链表数据排序的实现方案
嘿,我懂你现在的处境——在写带链表的程序,要按dd/mm/yyyy格式的过期日期里的月份排序展示,已经摸清楚用substr(3,2)提取月份子串,但还得把它转成整数,再结合链表排序来落地对吧?下面我给你一步步拆解实现思路和可直接用的代码示例:
第一步:提取月份并转换为整数
你找的提取月份的方法完全没问题,expireDate.substr(3,2)精准拿到了mm部分,接下来用std::stoi()就能把字符串转成整数用于比较。如果输入都是规范的dd/mm/yyyy格式,可以先写一个简单的辅助函数:
int getMonthFromExpireDate(const std::string& expireDate) { // 从索引3开始截取2个字符,拿到月份子串 std::string monthStr = expireDate.substr(3, 2); // 转换为整数返回 return std::stoi(monthStr); }
要是担心输入格式不规范,后续可以给这个函数加个校验逻辑,比如判断字符串长度、检查子串是否为数字之类的。
第二步:链表节点的定义
先假设你的链表节点结构是这样的(可以根据你实际存储的数据调整字段):
struct Node { std::string itemData; // 存储业务数据,比如商品信息 std::string expireDate; // 过期日期,格式dd/mm/yyyy Node* next; // 构造函数,方便创建节点 Node(std::string data, std::string ed) : itemData(data), expireDate(ed), next(nullptr) {} };
第三步:实现链表的月份排序
链表排序用冒泡排序或者插入排序都很合适,这里用冒泡排序举例子,逻辑直白好理解:
void sortLinkedListByMonth(Node** head) { if (*head == nullptr || (*head)->next == nullptr) { return; // 空链表或只有一个节点,直接返回 } bool swapped; Node* current; Node* sortedEnd = nullptr; // 标记已经排好序的链表末尾 do { swapped = false; current = *head; while (current->next != sortedEnd) { // 获取当前节点和下一个节点的月份 int currMonth = getMonthFromExpireDate(current->expireDate); int nextMonth = getMonthFromExpireDate(current->next->expireDate); // 按月份升序排序,要降序就改成currMonth < nextMonth if (currMonth > nextMonth) { // 交换两个节点的所有数据 std::swap(current->itemData, current->next->itemData); std::swap(current->expireDate, current->next->expireDate); swapped = true; } current = current->next; } sortedEnd = current; } while (swapped); }
如果你的节点数据量很大,交换节点指针会比交换数据更高效,不过逻辑稍微复杂一点,需要额外处理头节点的指向问题,这个版本先以简单易上手为主。
第四步:展示排序后的链表
写个遍历函数把排序后的结果打出来:
void printSortedList(Node* head) { Node* temp = head; while (temp != nullptr) { std::cout << "数据: " << temp->itemData << " | 过期日期: " << temp->expireDate << " | 月份: " << getMonthFromExpireDate(temp->expireDate) << std::endl; temp = temp->next; } }
测试示例
最后可以用一段测试代码验证功能:
int main() { // 创建测试节点 Node* head = new Node("零食礼包", "15/03/2025"); head->next = new Node("牛奶", "20/01/2025"); head->next->next = new Node("饼干", "05/05/2025"); head->next->next->next = new Node("面包", "10/02/2025"); std::cout << "排序前的链表:\n"; printSortedList(head); sortLinkedListByMonth(&head); std::cout << "\n按月份升序排序后的链表:\n"; printSortedList(head); // 记得释放内存,实际项目里别漏了 Node* tempNode; while (head != nullptr) { tempNode = head; head = head->next; delete tempNode; } return 0; }
内容的提问来源于stack exchange,提问作者beginner
相关产品推荐
相关产品推荐

