#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAXSIZE 50
typedef struct node{
int item;
struct node *next;
}node;
node *head = NULL;
int g_size = 0;
node * mk_node(int item)
{
node *p = (node *)malloc(sizeof(node));
if(p == NULL)
{
perror("malloc failure");
exit(1);
}
p->item = item;
p->next = NULL;
return p;
}
void free_node(node *p)
{
free(p);
p = NULL;
}
int isempty()
{
return g_size == 0;
}
int isfull()
{
return g_size == MAXSIZE;
}
int headinsert_node(node *p)
{
if(isempty())
{
head = p;
g_size++;
return TRUE;
}
if(isfull())
{
return FALSE;
}
p->next = head;
head = p;
g_size++;
return TRUE;
}
//尾插法
int tailinsert_node(node *p)
{
node *pre = head;
if(isempty())
{
head = p;
g_size++;
return TRUE;
}
if(isfull())
{
return FALSE;
}
while(pre->next != NULL)
{
pre = pre->next;
}
pre->next = p;
return TRUE;
}
//插入节点到指定节点的前边
int preinsert_node(node *p, node *local)
{
node *pre = head;
if(isempty())
{
return FALSE;
}
if(local == head)
{
headinsert_node(p);
g_size++;
return TRUE;
}
while(pre->next != local)
{
pre = pre->next;
}
p->next = local;
pre->next = p;
g_size++;
return TRUE;
}
//插入节点到指定节点的后边
int nextinsert_node(node *p, node *local)
{
node *next = head;
if(isfull())
{
return FALSE;
}
if(local->next == NULL)
{
tailinsert_node(p);
g_size++;
return TRUE;
}
while(local->next != next)
{
next = next->next;
}
p->next = next;
local->next = p;
g_size++;
return TRUE;
}
node * find_node(int item)
{
node *p = head;
/*printf("p = %p\n", p);
printf("p->next = %p\n", p->next);
printf("head = %p\n", head);*/
while(p != NULL)
{
if(p->item == item)
{
printf("find it\n");
return p;
}
p = p->next;
}
}
void rm_node(node *p)
{
node *pre = head;
if(head == p)
{
head = head->next;
return;
}
while(pre->next != NULL)
{
if(pre->next = p)
{
pre->next = p->next;
p->next = NULL;
}
pre = pre->next;
}
g_size--;
}
void destroy()
{
node *p;
while(head != NULL)
{
p = head;
head = head->next;
free_node(p);
}
printf("all node have remove\n");
g_size = 0;
}
void alternode(node *p, int item)
{
p->item = item;
}
void linktoarray(int *array)
{
node *p = head;
int i = 0;
while(p != NULL)
{
array[i] = p->item;
printf("array[%d] = %d ", i, array[i]);
printf("p->item = %d ", p->item);
p = p->next;
i++;
}
printf("\n");
}
void traverse(void)
{
node *p = head;
while(p != NULL)
{
printf("%d---%p\n", p->item, p);
p = p->next;
}
}
int main(void)
{
int i;
int *pstr;
int array[g_size];
memset(array, 0, g_size *sizeof(int));
node *p = mk_node(1);
headinsert_node(p);
p = mk_node(2);
headinsert_node(p);
p = mk_node(3);
headinsert_node(p);
p = mk_node(4);
headinsert_node(p);
p = mk_node(5);
headinsert_node(p);
p = mk_node(6);
tailinsert_node(p);
node *q = mk_node(7);
nextinsert_node(q, p);
//preinsert_node(q, p);
traverse();
alternode(q, 9);
traverse();
p = find_node(5);
rm_node(p);
traverse();
linktoarray(array);
destroy();
traverse();
return 0;
}