C++将数字各位存入链表类中
时间: 2023-08-04 13:17:52 浏览: 38
好的,下面是一个示例代码,可以将一个数字的各位数字存入链表中:
```c++
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* digitToList(int num) {
if (num == 0) {
return new ListNode(0);
}
ListNode *dummy = new ListNode(0);
ListNode *curr = dummy;
while (num > 0) {
curr->next = new ListNode(num % 10);
curr = curr->next;
num /= 10;
}
return dummy->next;
}
```
这个函数接受一个整数 `num` 作为参数,将其各个数字存入链表中并返回链表的头节点。例如,如果 `num` 为 123,那么函数将返回一个链表,其头节点的 `val` 属性为 1,第二个节点的 `val` 属性为 2,第三个节点的 `val` 属性为 3。
相关问题
设计一个链表类,链表类中的构造函数能将数字各位存入链表中
好的,以下是一个简单的链表类实现,它可以将一个数字的各位数字存储在链表中:
```c++
#include <iostream>
using namespace std;
class ListNode {
public:
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class LinkedList {
public:
ListNode* head;
LinkedList(int num) {
head = new ListNode(num % 10);
num /= 10;
ListNode* cur = head;
while(num != 0) {
cur->next = new ListNode(num % 10);
num /= 10;
cur = cur->next;
}
}
~LinkedList() {
ListNode* cur = head;
while(cur != NULL) {
ListNode* temp = cur;
cur = cur->next;
delete temp;
}
}
void print() {
ListNode* cur = head;
while(cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
};
int main() {
LinkedList l(123456);
l.print(); // 输出 6 5 4 3 2 1
return 0;
}
```
在这个实现中,我们首先将数字的个位存储在链表的头节点中,然后通过不断地除以 10,将数字的各个位依次存储在链表的后续节点中。在输出结果时,我们只需要从链表的头节点开始遍历,依次输出每个节点的值即可。
C++ 将共享指针存入链表
可以考虑使用 `std::shared_ptr` 和 `std::list` 来实现将共享指针存入链表。具体实现方法如下:
1. 定义一个 `std::list` 对象来存储共享指针:
```c++
std::list<std::shared_ptr<MyClass>> my_list;
```
2. 创建一个共享指针,并将其添加到链表中:
```c++
std::shared_ptr<MyClass> ptr(new MyClass);
my_list.push_back(ptr);
```
3. 遍历链表,访问共享指针指向的对象:
```c++
for (auto it = my_list.begin(); it != my_list.end(); ++it) {
(*it)->do_something();
}
```
其中,`MyClass` 是共享指针所指向的对象类型,`do_something()` 是 `MyClass` 的成员函数,可以根据实际需求进行修改。