C++之静态链表添加

tech2024-07-01  59

#include <iostream> #include <unistd.h> using namespace std; class Node { private: int num; static Node *head; Node *next; public: Node(int num); //~Node(); static void printList(); static void deleteList(); }; Node *Node::head = NULL; Node::Node(int num) { this->num = num; //next指向 next = head; head = this; } void Node::printList() { Node *p = head; while (p) { cout << p->num << endl; p = p->next; } } void Node::deleteList() { Node *p = head; while (p) { head = head->next; /* code */ p->next = NULL; delete p; p = head; } } int main() { for (int i = 0; i < 10; i++) { Node *node = new Node(i + 1000); } Node::printList(); Node::deleteList(); return 0; }

最新回复(0)