H
Haw Wang
Unregistered / Unconfirmed
GUEST, unregistred user!
第一段:
//: NESTED.H-- Nested struct in linked list
#ifndef NESTED_H_
#define NESTED_H_
struct stack {
struct link {
void* data;
link* next;
void initialize(void* Data, link* Next);
} * head;
void initialize ();
void push(void* Data);
void* peek();
void* pop();
void cleanup();
};
#endif //NESTED_H_
第二段:
//: NESTED.CPP -- Linked list with nesting
#include <stdlib.h>
#include <assert.h>
#include "nested.h"
void stack::link::initialize(
void* Data, link* Next) {
data = Data;
next = Next;
}
void stack::initialize() {head = 0;}
void stack:ush(void* Data) {
link* newlink = (link*)malloc(sizeof(link));
assert(newlink);
newlink->initialize(Data, head);
head = newlink;
}
void* stack:eek() { return head->data
}
void* stack:op() {
if(head==0) return 0;
void* result = head->data;
link* oldHead = head;
head = head->next;
free(oldHead);
return result;
}
void stack::cleanup() {
link* cursor = head;
while(head) {
cursor = cursor->next;
free(head->data)
//Assume a malloc!
free(head);
head = cursor;
}
}
我试着想用一个类来实现这个栈,但不成功,想看看各位大虾的高着。
//: NESTED.H-- Nested struct in linked list
#ifndef NESTED_H_
#define NESTED_H_
struct stack {
struct link {
void* data;
link* next;
void initialize(void* Data, link* Next);
} * head;
void initialize ();
void push(void* Data);
void* peek();
void* pop();
void cleanup();
};
#endif //NESTED_H_
第二段:
//: NESTED.CPP -- Linked list with nesting
#include <stdlib.h>
#include <assert.h>
#include "nested.h"
void stack::link::initialize(
void* Data, link* Next) {
data = Data;
next = Next;
}
void stack::initialize() {head = 0;}
void stack:ush(void* Data) {
link* newlink = (link*)malloc(sizeof(link));
assert(newlink);
newlink->initialize(Data, head);
head = newlink;
}
void* stack:eek() { return head->data
}
void* stack:op() {
if(head==0) return 0;
void* result = head->data;
link* oldHead = head;
head = head->next;
free(oldHead);
return result;
}
void stack::cleanup() {
link* cursor = head;
while(head) {
cursor = cursor->next;
free(head->data)
//Assume a malloc!
free(head);
head = cursor;
}
}
我试着想用一个类来实现这个栈,但不成功,想看看各位大虾的高着。