c++链表怎么写
C++链表可以使用结构体或者类来实现。以下是使用结构体的示例:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = NULL;
}
// 在链表尾部插入节点
void insert(int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
return;
}
Node* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
// 在链表中查找节点
Node* search(int val) {
Node* cur = head;
while (cur != NULL && cur->data != val) {
cur = cur->next;
}
return cur;
}
// 删除节点
void remove(int val) {
if (head == NULL) {
return;
}
if (head->data == val) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* cur = head;
while (cur->next != NULL && cur->next->data != val) {
cur = cur->next;
}
if (cur->next != NULL) {
Node* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
}
// 打印链表
void print() {
Node* cur = head;
while (cur != NULL) {
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.print(); // 1 2 3
Node* node = list.search(2);
if (node != NULL) {
cout << "Found node with value " << node->data << endl;
} else {
cout << "Node not found" << endl;
}
list.remove(2);
list.print(); // 1 3
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bZkR 著作权归作者所有。请勿转载和采集!