用C++写程序1.实现带头结点的单链表的建立、求长度,取元素、修改元素、插入、删除等单链表的基本操作。 2.多项式的乘法,已知2个多项式,设计一个算法完成2个多项式的乘法。
时间: 2024-10-16 09:22:17 浏览: 54
在C++中,我们可以使用结构体(struct)来定义单链表节点,并实现一些基本操作:
```cpp
// 定义链表节点
struct ListNode {
int val; // 节点值
ListNode* next; // 指向下一个节点的指针
};
// 创建空链表
ListNode* createList() {
return nullptr;
}
// 链表长度
int length(ListNode* head) {
int count = 0;
while (head != nullptr) {
++count;
head = head->next;
}
return count;
}
// 取元素
int get(int index, ListNode* head) {
if (index < 0 || index >= length(head)) {
throw std::out_of_range("Index out of range");
}
ListNode* current = head;
for (int i = 0; i < index; ++i) {
current = current->next;
}
return current->val;
}
// 修改元素
void set(int index, int newValue, ListNode*& head) {
if (index < 0 || index >= length(head)) {
throw std::out_of_range("Index out of range");
}
ListNode* current = head;
for (int i = 0; i < index; ++i) {
current = current->next;
}
current->val = newValue;
}
// 插入元素
void insert(int index, int value, ListNode*& head) {
if (index <= 0) {
new ListNode{value, head};
head = head->next;
} else {
ListNode* newNode = new ListNode{value};
ListNode* prevNode = head;
for (int i = 0; i < index - 1 && prevNode != nullptr; ++i) {
prevNode = prevNode->next;
}
if (prevNode == nullptr) {
throw std::out_of_range("Invalid insertion position");
}
newNode->next = prevNode->next;
prevNode->next = newNode;
}
}
// 删除元素
void deleteElement(int index, ListNode*& head) {
if (index < 0 || index >= length(head)) {
throw std::out_of_range("Index out of range");
}
if (index == 0) {
head = head->next;
} else {
ListNode* curr = head;
for (int i = 0; i < index - 1; ++i) {
curr = curr->next;
}
curr->next = curr->next->next;
}
}
// 多项式乘法示例(简化版)
class Polynomial {
private:
struct Term {
int coef;
int exp;
};
vector<Term> terms;
public:
void multiply(Polynomial& other) {
for (const auto& term : terms) {
for (const auto& otherTerm : other.terms) {
if (term.exp + otherTerm.exp > MAX_EXPONENT) {
break; // 如果指数过大,避免整数溢出
}
terms.push_back({term.coef * otherTerm.coef, term.exp + otherTerm.exp});
}
}
}
friend std::ostream& operator<<(std::ostream& os, const Polynomial& poly);
};
std::ostream& operator<<(std::ostream& os, const Polynomial& poly) {
os << "Polynomial [";
for (size_t i = 0; i < poly.terms.size(); ++i) {
if (i > 0) {
os << "+ ";
}
os << poly.terms[i].coef << "x^" << poly.terms[i].exp;
}
os << "]";
return os;
}
```
阅读全文