#include using namespace std;

// 定义链表节点 struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} };

// 在带表头结点的单链表中寻找一个数 int findNumber(ListNode* head, int target) { ListNode* cur = head->next; int position = 1; while (cur != NULL) { if (cur->val == target) { return position; } cur = cur->next; position++; } return 0; }

int main() { // 输入原始数列 int num; ListNode* dummy = new ListNode(0); // 表头结点 ListNode* tail = dummy; while (cin >> num) { ListNode* node = new ListNode(num); tail->next = node; tail = tail->next; }

// 输入需要找的数
int target;
cin >> target;

// 在链表中寻找目标数
int position = findNumber(dummy, target);

// 输出结果
cout << position << endl;

return 0;
描述试编写一个算法在带表头结点的单链表中寻找一个数。若找到则函数返回该数在列表中的地址i 1~n;若找不到则函数返回0。输入描述第一行 原始数列;第二行 需要找的数输出描述找到则输出数在数列中的位置第一个位置输出1依次类推若没有找到输出0希望能用c++编写代码一定要正确哦!

原文地址: https://www.cveoy.top/t/topic/iQ0A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录