/* linkedlist.h */
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
typedef struct node *link;
typedef unsigned char ElemType;
struct node {
ElemType item;
link next;
};
link make_node(ElemType item);
void free_node(link p);
link search(ElemType key);
void insert(link p);
void delete(link p);
void traverse(void (*visit) (link));
void reverse(void);
void destroy(void);
void push(link p);
link pop(void);
void enqueue(link p);
link denqueue(void);
#endif
/* linkedlist.c */
#include
#include "linkedlist.h"
static link head = NULL;
link make_node(ElemType item)
{
link p = malloc(sizeof *p);
p->item = item;
p->next = NULL;
return p;
}
void free_node(link p)
{
free(p);
}
link search(ElemType key)
{
link p;
for (p = head; p; p = p->next)
if (p->item == key)
return p;
return NULL;
}
void insert(link p)
{
p->next = head;
head = p;
}
void delete(link p)
{
link pre;
if (p == head) {
head = p->next;
return;
}
for (pre = head; pre; pre = pre->next)
if (pre->next == p) {
pre->next = p->next;
return;
}
}
void traverse(void (*visit) (link))
{
link p;
for (p = head; p; p = p->next)
visit(p);
}
void reverse(void)
{
link prev,next;
if(!head ||!head->next)
return;
prev=NULL;
while(head->next)
{
next=head->next;
head->next=prev;
prev=head;
head=next;
}
head->next=prev;
}
void destroy(void)
{
link q, p = head;
head = NULL;
while (p) {
q = p;
p = p->next;
free_node(q);
}
}
void push(link p)
{
insert(p);
}
link pop(void)
{
if (head == NULL)
return NULL;
else {
link p = head;
head = head->next;
return p;
}
}
void enqueue(link p)
{
if(!p)
return;
insert(p);
}
link denqueue(void)
{
link pre=NULL,tail=NULL;
if(!head)
return NULL;
tail=head;
while(tail->next)
{
pre=tail;
tail=tail->next;
}
if(head==tail)
{
head=NULL;
}
else
{
pre->next=NULL;
}
return tail;
}
/* main.c */
#include
#include "linkedlist.h"
void print_item(link p)
{
printf("%d\n", p->item);
}
int main(void)
{
link p = make_node(10);
insert(p);
p = make_node(5);
insert(p);
p = make_node(90);
insert(p);
p = search(5);
delete(p);
free_node(p);
traverse(print_item);
destroy();
p = make_node(100);
push(p);
p = make_node(200);
push(p);
p = make_node(250);
push(p);
reverse();
while (p = pop()) {
print_item(p);
free_node(p);
};
p = make_node(10);
enqueue(p);
p = make_node(20);
enqueue(p);
p = make_node(50);
enqueue(p);
while (p =denqueue()) {
print_item(p);
free_node(p);
};
return 0;
}
阅读(1371) | 评论(0) | 转发(0) |