分别用顺序表和单链表的存储形式实现以下操作:(两个独立程序)
1.将空的线性表L完成输入操作,各个数据元素值从键盘输入;
2. 使得所有数据元素按非递减有序排列;
3. 查找值为x的元素,返回它在线性表中的位置,0表示查找失败;
4. 删除值为x的元素;
5. 插入元素x,并使线性表L仍需保持有序。
6. 显示线性表L中所有元素。
7.需提供线性表的其他基本操作,如初始化、求线性表长度等
怎么用c++来实现?
数据结构问题,求大神帮忙
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答
- qq_36273221 2023-05-10 15:09关注
以下是两种数据结构的实现:顺序表和单链表。这两种实现都满足了上述的七个要求。
首先,我们用顺序表(动态数组)实现:
#include <iostream> #include <vector> #include <algorithm> class OrderedList { public: OrderedList() : data({}) {} void input() { std::cout << "Enter number of elements: "; int n; std::cin >> n; data.resize(n); std::cout << "Enter elements: "; for (int i = 0; i < n; i++) std::cin >> data[i]; sort(); } void sort() { std::sort(data.begin(), data.end()); } int find(int x) { auto it = std::find(data.begin(), data.end(), x); if (it != data.end()) return it - data.begin() + 1; else return 0; } void remove(int x) { auto it = std::remove(data.begin(), data.end(), x); data.erase(it, data.end()); } void insert
接下来,我们用单链表实现
#include <iostream> class Node { public: int val; Node* next; Node(int val) : val(val), next(NULL) {} }; class LinkedList { public: LinkedList() : head(NULL), length(0) {} void input() { std::cout << "Enter number of elements: "; int n; std::cin >> n; std::cout << "Enter elements: "; for (int i = 0; i < n; i++) { int x; std::cin >> x; insert(x); } } int find(int x) { Node* curr = head; int index = 1; while (curr) { if (curr->val == x) return index; curr = curr->next; index++; } return 0; } void remove(int x) { Node** indirect = &head; while ((*indirect) && (*indirect)->val != x) indirect = &((*indirect)->next); if (*indirect) { Node* toDelete = *indirect; *indirect = (*indirect)->next; delete toDelete; length--; } } void insert(int x) { Node** indirect = &head; while ((*indirect) && (*indirect)->val < x) indirect = &((*indirect)->next); Node* newNode = new Node(x); newNode->next = *indirect; *indirect = newNode; length++; } void display() { Node* curr = head; while (curr) { std::cout << curr->val << ' '; curr = curr->next; } std::cout << '\n'; } int size() { return length; } private: Node* head; int length; };
解决 无用评论 打赏 举报