在Linux中使用C++實現數據結構,你需要遵循以下步驟:
安裝開發環境:
創建項目目錄:
編寫C++代碼:
data_structures.cpp。實現數據結構:
編譯代碼:
data_structures.cpp,你可以使用以下命令編譯它:g++ -o data_structures data_structures.cpp
data_structures的可執行文件。運行程序:
./data_structures
下面是一個簡單的鏈表實現的例子:
#include <iostream>
// 定義鏈表節點結構
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
// 定義鏈表類
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
// 添加元素到鏈表頭部
void push(int val) {
Node* newNode = new Node(val);
newNode->next = head;
head = newNode;
}
// 打印鏈表
void printList() {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
}
// 析構函數,釋放內存
~LinkedList() {
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
}
};
int main() {
LinkedList list;
list.push(1);
list.push(2);
list.push(3);
list.printList(); // 應該打印出 3 2 1
return 0;
}
將上述代碼保存到data_structures.cpp文件中,然后按照前面的步驟編譯和運行它。這將創建一個簡單的鏈表,并添加三個元素到鏈表中,然后打印出鏈表的內容。