设计一个链表类,链表类中的构造函数能将数字各位存入链表中
时间: 2023-07-10 10:18:56 浏览: 38
好的,以下是一个简单的链表类实现,它可以将一个数字的各位数字存储在链表中:
```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,将数字的各个位依次存储在链表的后续节点中。在输出结果时,我们只需要从链表的头节点开始遍历,依次输出每个节点的值即可。