按头和尾输入线性表各数据元素的值,建立两个链表。分别删除将两个链表中值最大和最小的结点,要求给出C/C++代码
时间: 2024-11-15 12:23:29 浏览: 0
在C++中,我们可以创建一个双向链表节点结构,并编写函数来实现按头和尾插入元素、删除最大和最小值的节点。首先,我们定义一个双向链表节点:
```cpp
template <typename T>
struct ListNode {
T value;
ListNode* prev;
ListNode* next;
ListNode(T val) : value(val), prev(nullptr), next(nullptr) {}
};
```
接下来,我们定义一些操作链表的函数:
1. 插入头节点:
```cpp
void insertAtHead(ListNode<T>* &list, const T& value) {
ListNode<T> *newNode = new ListNode<T>(value);
newNode->next = list;
if (list != nullptr)
list->prev = newNode;
list = newNode;
}
```
2. 插入尾节点:
```cpp
void insertAtTail(ListNode<T>** &head, const T& value) {
ListNode<T> *newNode = new ListNode<T>(value);
if (*head == nullptr) {
*head = newNode;
return;
}
ListNode<T> *last = *head;
while (last->next != nullptr)
last = last->next;
last->next = newNode;
newNode->prev = last;
}
```
3. 删除最大值节点:
```cpp
ListNode<T>* deleteMaxNode(ListNode<T>** head) {
if (*head == nullptr || (*head)->next == nullptr)
return *head;
ListNode<T>* maxNode = *head;
for (ListNode<T> *current = *head; current->next != nullptr; current = current->next) {
if (current->value > maxNode->value)
maxNode = current;
}
if (maxNode == *head) {
*head = maxNode->next;
if (*head)
(*head)->prev = nullptr;
} else {
maxNode->prev->next = maxNode->next;
if (maxNode->next)
maxNode->next->prev = maxNode->prev;
}
delete maxNode;
return nullptr;
}
```
4. 删除最小值节点:
```cpp
ListNode<T>* deleteMinNode(ListNode<T>** tail) {
if (*tail == nullptr || (*tail)->prev == nullptr)
return *tail;
ListNode<T>* minNode = *tail;
for (ListNode<T> *current = *tail; current->prev != nullptr; current = current->prev) {
if (current->value < minNode->value)
minNode = current;
}
if (minNode == *tail) {
*tail = minNode->prev;
if (*tail)
(*tail)->next = nullptr;
} else {
minNode->next->prev = minNode->prev;
if (minNode->prev)
minNode->prev->next = minNode->next;
}
delete minNode;
return nullptr;
}
```
阅读全文