好友
阅读权限10
听众
最后登录1970-1-1
|
list.h
---------------------------------------------------------#define NULL 0
typedef int ElemType;
typedef struct _Node
{
ElemType data;
struct _Node *next;
}Node;
typedef struct
{
Node *head;
}List;
List *InitList();
void DestroyList(List **p);
Node *CreatNewNode(ElemType *pdata);
Node *GetCurAddr(List *p, int n);
int InsertNode(List *p, int n, ElemType *pdata);
int AppendList(List *p, ElemType *pdata);
int DeleteNode(List *p, int n);
int ModifyNode(List *p, int n, ElemType *pdata);
void TraverseList(List *p, void(*mpf)(ElemType *pdata));
list.c
---------------------------------------------------------
#include "list.h"
ElemType pdata;
List *InitList()
{
List *p = NULL;
Node *temp = NULL;
p = (List *)malloc(sizeof(List));
if(!p)
{
return p;
}
temp = CreatNewNode(&pdata);
if(!temp)
{
free(p);
p = NULL;
return p;
}
p->head = temp;
temp->next = NULL;
return p;
}
void DestroyList(List **p)
{
Node *temp = NULL;
Node *destroy = NULL;
if(*p)
{
temp = (*p)->head;
while(temp)
{
destroy = temp;
temp = temp->next;
free(destroy);
}
free(*p);
*p = NULL;
}
}
Node *CreatNewNode(ElemType *pdata)
{
Node *temp = NULL;
temp = (Node *)malloc(sizeof(Node));
if(!temp)
{
return temp;
}
memcpy(temp, pdata, sizeof(ElemType));
return temp;
}
Node *GetCurAddr(List *p, int n)/*1-n*/
{
Node *temp = p->head;
int i = 0;
while(temp&&i<n)
{
i++;
temp = temp->next;
}
if(!temp || i>n)
{
return NULL;
}
return temp;
}
int InsertNode(List *p, int n, ElemType *pdata)
{
Node *new = NULL;
Node *addr = NULL;
new = CreatNewNode(pdata);
if(!new)
{
return 0;
}
addr = GetCurAddr(p,n-1);
if(!addr)
{
return 0;
}
new->next = addr->next;
addr->next = new;
return 1;
}
int AppendList(List *p, ElemType *pdata)
{
Node *new = NULL;
Node *temp = p->head;
Node *last = p->head;
new = CreatNewNode(pdata);
if(!new)
{
return 0;
}
while(temp)
{
last = temp;
temp = temp->next;
}
new->next = NULL;
last->next = new;
return 1;
}
int DeleteNode(List *p, int n)
{
Node *temp = NULL;
Node *addr = NULL;
addr = GetCurAddr(p, n-1);
if(!addr || !addr->next)
{
return 0;
}
temp = addr->next;
addr->next = addr->next->next;
free(temp);
return 1;
}
int ModifyNode(List *p, int n, ElemType *pdata)
{
Node *addr = NULL;
addr = GetCurAddr(p,n);
if(!addr)
{
return 0;
}
if(addr == p->head)
{
return 0;
}
memcpy(addr, pdata, sizeof(ElemType));
return 1;
}
void TraverseList(List *p, void(*mpf)(ElemType *pdata))
{
Node *temp = p->head->next;
while(temp)
{
mpf(&temp->data);
temp = temp->next;
}
}
|
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|