主函数文件
main.cpp
#include <iostream>
#include "list_src.h"
using namespace std;
int main(){
Node* head = init_list();
for(int i=0; i<10; i++){
add_node(head, i);
}
printf_list(head);
int find_num = 9;
Node* pl = find_node(head, find_num);
if(pl){
cout<<"find_num[ "<<find_num<<" ]找到了"<<endl;
dlete_node(head, find_num);
printf_list(head);
}else{
cout<<"find_num[ "<<find_num<<" ]未找到"<<endl;
}
rever_list(head);
cout<<"反转链表后: ";
printf_list(head);
clean_list_node(head);
cout<<"phead->next = NULL之后,链表长度count:"<<count<<endl;
cout<<"phead->next = NULL之后,head->next:"<<head->next<<endl;
cout<<"清空链表节点后:";
printf_list(head);
clean_list(head);
if(head){
free(head);
head = NULL;
}
printf_list(head);
cout<<"==========>"<<count<<endl;
return 0;
}
成员函数定义文件
dingyi.cpp
#include <iostream>
#include "list_src.h"
Node* init_list(){
Node* head = (Node*)malloc(sizeof(Node));
if(NULL == head){
cout<<"head malloc error"<<endl;
exit(-1);
}
head->next = NULL;
return head;
}
void add_node(Node* phead, int num){
Node* pnew = (Node*)malloc(sizeof(Node));
if(NULL == pnew){
cout<<"pnew malloc error"<<endl;
exit(-1);
}
pnew->data = num;
pnew->next = phead->next;
phead->next = pnew;
count++;
}
Node* find_node(Node* phead, int num){
Node* cur = phead->next;
while(cur){
if(cur->data == num){
return cur;
}
cur = cur->next;
}
return NULL;
}
void dlete_node(Node* phead, int num){
Node* pre = phead;
Node* cur = phead->next;
while(cur->data != num){
cur = cur->next;
pre = pre->next;
}
pre->next = cur->next;
free(cur);
cur = NULL;
count--;
}
void printf_list(Node* phead){
if(!phead){
cout<<"链表已销毁,无需打印"<<endl;
}else{
if(phead->next){
Node* cur = phead->next;
while(cur){
cout<<cur->data<<" ";
cur = cur->next;
}
cout<<"链表长度:"<<count<<endl;
}
else{
cout<<"链表只有头节点,无需打印,count的值是:"<<count<<endl;
}
}
}
void clean_list_node(Node* phead){
Node* cur = phead->next;
Node* tmp = NULL;
while(cur){
tmp = cur->next;
free(cur);
cur = tmp;
count--;
}
cout<<"phead->next = NULL之前,链表长度:"<<count<<endl;
cout<<"phead->next = NULL之前,phead->next:"<<phead->next<<endl;
phead->next = NULL;
}
void clean_list(Node* phead){
Node* cur = NULL;
while(phead){
cur = phead->next;
free(phead);
count--;
phead = cur;
}
cout<<"销毁链表之后,phead: "<<phead<<endl;
}
void rever_list(Node* phead){
Node* cur = phead->next;
phead->next = NULL;
Node* tmp = NULL;
while(cur){
tmp = cur;
cur = cur->next;
tmp->next = phead->next;
phead->next = tmp;
}
}
声明文件
shengming.h
#ifndef _LIST_SRC_H
#define _LIST_SRC_H
#include <stdlib.h>
using namespace std;
typedef struct _node{
int data;
struct _node* next;
}Node;
static int count = 0;
Node* init_list();
void add_node(Node* phead, int num);
Node* find_node(Node* phead, int num);
void dlete_node(Node* phead, int num);
void printf_list(Node* phead);
void clean_list_node(Node* phead);
void clean_list(Node* phead);
void rever_list(Node* phead);
#endif