实现线性表的链式存储定义,完成单链表的创建(头插法、尾插法)、插入、删除、查找等常用操作
时间: 2023-09-30 19:07:54 浏览: 129
链式线性表的建立、插入及删除
5星 · 资源好评率100%
线性表的链式存储定义:
```c++
template <typename T>
struct ListNode {
T val;
ListNode *next;
ListNode(T x) : val(x), next(nullptr) {}
};
```
单链表的创建(头插法、尾插法):
```c++
template <typename T>
ListNode<T>* createListHead(vector<T>& nums) {
ListNode<T> *head = new ListNode<T>(0);
for (int i = 0; i < nums.size(); i++) {
ListNode<T> *node = new ListNode<T>(nums[i]);
node->next = head->next;
head->next = node;
}
return head->next;
}
template <typename T>
ListNode<T>* createListTail(vector<T>& nums) {
ListNode<T> *head = new ListNode<T>(0);
ListNode<T> *tail = head;
for (int i = 0; i < nums.size(); i++) {
ListNode<T> *node = new ListNode<T>(nums[i]);
tail->next = node;
tail = node;
}
tail->next = nullptr;
return head->next;
}
```
插入操作:
```c++
template <typename T>
void insertNode(ListNode<T> *prev, T val) {
ListNode<T> *node = new ListNode<T>(val);
node->next = prev->next;
prev->next = node;
}
```
删除操作:
```c++
template <typename T>
void deleteNode(ListNode<T> *prev) {
ListNode<T> *node = prev->next;
prev->next = prev->next->next;
delete node;
}
```
查找操作:
```c++
template <typename T>
ListNode<T>* searchNode(ListNode<T> *head, T val) {
ListNode<T> *node = head;
while (node != nullptr) {
if (node->val == val) return node;
node = node->next;
}
return nullptr;
}
```
阅读全文