main.cpp
#include <stdio.h>
#include "SingleList.h"
int main(int argc, int *argv[])
{
Node *pHead = NULL;
for (int i = 0; i < 10; i++)
{
Node node;
node.id = i;
pHead = AddNode(pHead, node);
}
PrintList(pHead);
Node *tmp = FindNode(pHead, 5);
if (NULL != tmp)
{
printf("\n\n%d\t\t%p\n\n", tmp->id, tmp->next);
}
Node node;
node.id = 5;
pHead = DeleteNode(pHead, node);
PrintList(pHead);
return 0;
}
SingleList.h
#ifndef SINGLE_LIST
#define SINGLE_LIST
typedef struct Node{
int id;
Node *next;
}Node;
enum ReturnStatus{
SingleList_Success = 0,
SingleList_Error
};
Node* FreeList();
Node* AddNode(Node *pHead, Node node);
Node* DeleteNode(Node *pHead, Node node);
Node* FindNode(Node *pHead, int id);
int ModifyNode(Node *pHead, Node node);
void PrintList(Node *pHead);
#endif
SingleList.cpp
#include <stdio.h>
#include <stdlib.h>
#include "SingleList.h"
Node* FreeList(Node *pHead)
{
while(NULL != pHead)
{
Node *tmp = pHead;
pHead = pHead->next;
delete tmp;
}
return NULL;
}
Node* AddNode(Node *pHead, Node node)
{
Node *tmp = (Node*)malloc(sizeof(Node));
if(NULL == tmp)
{
return NULL;
}
//在链表头部插入新节点
tmp->id = node.id;
tmp->next = pHead;
pHead = tmp;
return pHead;
}
Node* DeleteNode(Node *pHead, Node node)
{
if (NULL == pHead)
{
return NULL;
}
//删除的节点为首节点
if(pHead->id == node.id)
{
delete pHead;
pHead = NULL;
}
else
{
#if 0
Node *pre = pHead;
Node *cur = pHead->next;
while(NULL != cur)
{
if (cur->id == node.id)
{
pre->next = cur->next;
delete cur;
return pHead;
}
else
{
pre = cur;
cur = cur->next;
}
}
#else
Node *pre = pHead;
for (Node *cur = pHead->next; NULL != cur; pre = cur,cur = cur->next)
{
if (cur->id == node.id)
{
pre->next = cur->next;
delete cur;
return pHead;
}
}
#endif
}
return pHead;
}
Node* FindNode(Node *pHead, int id)
{
for (Node *tmp = pHead; NULL != tmp; tmp = tmp->next)
{
if(tmp->id == id)
{
return tmp;
}
}
return NULL;
}
int ModifyNode(Node *pHead, Node node)
{
Node *dest = FindNode(pHead, node.id);
if(NULL != dest)
{
//更新节点内容
return SingleList_Success;
}
return SingleList_Error;
}
void PrintList(Node *pHead)
{
for (Node *tmp = pHead; NULL != tmp; tmp = tmp->next)
{
printf("%d\t\t%p\n", tmp->id, tmp->next);
}
}