-
#include <iostream>
-
#include <stdlib.h>
-
-
using namespace std;
-
-
struct node_t {
-
int data;
-
struct node_t *next;
-
};
-
struct list_t {
-
struct node_t* head;
-
struct node_t* tail;
-
int size;
-
};
-
-
struct list_t* init_list() {
-
struct list_t* list = (struct list_t*)malloc(sizeof(struct list_t));
-
list->head = list->tail = NULL;
-
list->size = 0;
-
return list;
-
}
-
-
int insert_list_end(node_t *node, struct list_t *list) {
-
if (list->tail == NULL) {
-
list->tail = list->head = node;
-
}
-
else {
-
list->tail->next = node;
-
list->tail = node;
-
}
-
list->size++;
-
return 1;
-
}
-
-
int insert_list_head(node_t *node, struct list_t *list) {
-
if (list->head == NULL) {
-
list->head = list->tail = node;
-
}
-
else {
-
node->next = list->head;
-
list->head = node;
-
}
-
list->size++;
-
return 1;
-
}
-
-
struct node_t* remove_list_head(struct list_t *list) {
-
node_t *node = NULL;
-
if (list->head != NULL) {
-
node = list->head;
-
if (list->head == list->tail) {
-
list->tail = list->head->next;
-
}
-
list->head = list->head->next;
-
list->size--;
-
}
-
return node;
-
}
-
struct node_t *remove_list_end(struct list_t *list) {
-
node_t *node = NULL;
-
if (list->tail != NULL) {
-
node = list->tail;
-
if (list->head == list->tail) {
-
list->head = list->tail->next;
-
list->tail = list->head;
-
}
-
else {
-
node_t *p = list->head;
-
while ( p->next != list->tail) {
-
p = p->next;
-
}
-
p->next = list->tail->next;
-
list->tail = p;
-
}
-
list->size--;
-
}
-
return node;
-
}
-
-
int remove_list_node(struct node_t *node, struct list_t *list) {
-
if (node == list->head ) {
-
return (remove_list_head(list) != NULL);
-
}
-
else if (node == list->tail) {
-
return (remove_list_end(list) != NULL);
-
}
-
struct node_t *p= list->head;
-
while (p->next != NULL && p->next != node ) {
-
p = p->next;
-
}
-
if (p->next == NULL) {
-
return 0;
-
}
-
p->next = p->next->next;
-
list->size--;
-
return 1;
-
}
-
-
void output_list(struct list_t *list) {
-
node_t *node = list->head;
-
while (node != NULL) {
-
cout<<node->data<<" ";
-
node = node->next;
-
}
-
cout<<endl;
-
}
-
-
int main(int argc, char **argv) {
-
int a = 10;
-
if (argc > 1) {
-
a = atoi(argv[1]);
-
}
-
struct list_t* list = init_list();
-
cout<<"before insert:";
-
output_list(list);
-
for (int i = 0; i < a; i++) {
-
node_t *node = new node_t;
-
int n = rand() % (a*10);
-
node->data = n;
-
node->next = NULL;
-
insert_list_head(node, list);
-
node = new node_t;
-
node->data = n;
-
node->next = NULL;
-
insert_list_end(node, list);
-
}
-
cout<<"list.size:"<<list->size<<" after insert:";
-
output_list(list);
-
for (int i = 0; i < a; i++) {
-
delete remove_list_head(list);
-
delete remove_list_end(list);
-
}
-
cout<<"list.size:"<<list->size<<" after delete:";
-
output_list(list);
-
return 0;
- }