1. 节点数据结构为:
struct Node {
void *data;
Node *next;
} *head;
2. list操作函数:
bool add(void*);
bool del(void*);
bool insert(void*, void*);
void traversal();
int length() const;
3. 头文件(utils.hpp)实现如下所示:
namespace utils {
class List {
private:
struct Node {
void *data;
Node *next;
} *head;
int size;
public:
List();
~List();
bool add(void*);
bool del(void*);
bool insert(void*, void*);
void traversal();
int length() const;
};
}
4. 实现实现上述结构代码为(utils.cpp)
#include <iostream>
#include <cassert>
#include <stdio.h>
#include "utils.hpp"
using namespace std;
using namespace utils;
List::List() {
this->head = NULL;
this->size = 0;
}
bool List::add(void *data) {
Node *node = (struct Node*) malloc(sizeof(struct Node));
if (node == NULL) {
return false;
}
node->next = NULL;
node->data = data;
this->size += 1;
if (head == NULL) {
head = node;
return true;
}
node->next = head;
head = node;
return true;
}
bool List::del(void *data) {
struct Node *curr = this->head;
if (this->head == NULL) {
fprintf(stderr, "list is empty\n");
return false;
}
if (curr->data == data) {
this->head = curr->next;
free(curr);
this->size -= 1;
return true;
}
struct Node *prev = curr;
curr = curr->next;
while ( true ) {
if (curr != NULL && curr->data == data) {
prev->next = curr->next;
free(curr);
this->size -= 1;
return true;
}
prev = curr;
curr = curr->next;
if (curr == NULL) {
break;
}
}
return false;
}
bool List::insert(void *obj, void *target) {
struct Node *loop = this->head;
if (this->head == NULL) {
fprintf(stderr, "list is empty\n");
return false;
}
while ( true ) {
if (loop->data == obj) {
struct Node *node = (struct Node*) malloc(sizeof(struct Node));
node->data = target;
node->next = loop->next;
loop->next = node;
this->size += 1;
return true;
}
loop = loop->next;
if (loop == NULL) {
fprintf(stderr, "can't find target object\n");
return false;
}
}
return false;
}
void List::traversal() {
struct Node *loop = this->head;
int counter = 0;
while ( true ) {
if (loop == NULL) {
break;
}
printf("%d\t%s\n", ++counter, (char*) loop->data);
loop = loop->next;
}
}
inline int List::length() const {
return this->size;
}
List::~List() {
if (this->size == 0) {
return;
}
struct Node *loop = this->head;
fprintf(stderr, "List desconstructor called %s\n", (char*) loop->data);
while ( loop != NULL) {
free(loop);
loop = loop->next;
}
}
void testList() {
List list;
const char *first = "hello";
const char *second = "world";
const char *com = "!";
const char *non = "xx";
list.add((void*) first);
list.add((void*) com);
list.insert((void*) first, (void*) second);
cout << list.del((void*) com) << endl;
cout << list.del((void*) first) << endl;
cout << list.del((void*) second) << endl;
cout << "list length: " << list.length() << endl;
/*
cout << "list length: " << list.length() << endl;
*/
}
int main() {
testList();
}