#include <string>
#include <iostream>
using namespace std;
class ListNode {
public:
int val;
ListNode* next;
ListNode(int value) {
val = value;
next = nullptr;
}
};
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
if (slow != fast && fast != nullptr && fast->next != nullptr) {
slow = slow->next;
}
return slow;
}
};
int main()
{
ListNode* head = nullptr; // 初始化一个空链表
ListNode* current = nullptr; // 用于追踪链表的当前节点
cout << "请输入链表的元素(以0结束):" << endl;
int value;
cin >> value;
while (value != 0)
{
ListNode* newNode = new ListNode(value); // 创建新节点
if (head == nullptr) {
head = newNode; // 第一个节点,设置为头节点
}
else
{
current->next = newNode; // 将新节点链接到当前节点后面
}
current = newNode; // 更新当前节点为新节点
cin >> value;
}
Solution solution;
ListNode* middle = solution.middleNode(head);
// 输出中间节点的值
if (middle != nullptr) {
cout << "The middle node is: " << middle->val << endl;
}
else {
cout << "链表为空或节点数为偶数,没有中间节点。" << endl;
}
// 释放链表内存,避免内存泄漏
current = head;
while (current != nullptr) {
ListNode* temp = current;
current = current->next;
delete temp;
}
}
链表中间节点(C++)
最新推荐文章于 2024-08-24 16:18:08 发布