自己写的单链表
link.c
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#include? "link.h"/****? 這是一個計算HASH值的算法**/
int time33(char* arKey,int arlength){int h = 0;int i;for(i=0;i<arlength;i++){h = h*33 + (int)*arKey++;}return h;?? ?
}//創建節點
struct node* createNode(char* key,char* s)
{int node_key=0;//強制轉換,假如使用(void* value)//char* arKey = (char*)key;int len =strlen(key);struct node* new_node=(struct node*)malloc(sizeof(struct node));if(new_node==NULL){printf("內存分配失敗\n");}memset(new_node,0,sizeof(new_node));node_key = time33(key,len);new_node->value=node_key;new_node->string=s;new_node->next=NULL;return new_node;
}//新增節點
void add(struct node* head,char* key,char* s)
{struct node* new_node=createNode(key,s);while(head->next!=NULL){head=head->next;}head->next=new_node;
}//搜索節點
char* searchNode(struct node* head,char* key)
{int len = strlen(key);int node_key = time33(key,len);while(head->next!=NULL){if(head->value==node_key){return head->string;}head=head->next;}return NULL;
}//刪除節點
int deleteNode(struct node* head,char* key)
{int i=0;int len = strlen(key);int node_key = time33(key,len);while(head->next->next!=NULL){if(head->next->value==node_key){struct node* d_node=head->next;head->next=head->next->next;free(d_node);return i;}i++;head=head->next;}return 0;
}//主文件
int main()
{int d1=0;char* s1;struct node* head=createNode("0","0");add(head,"aa","aaa");add(head,"bb","bbb");add(head,"cc","ccc");add(head,"dd","ddd");add(head,"ee","eee");add(head,"ff","fff");s1=searchNode(head,"cc");d1=deleteNode(head,"bb");return 0;
}link.h
#define HASHSIZE 13
struct node{
int value;
char* string;
struct node* next;
};
總結
- 上一篇: 利用Apache的ab命令做Benchm
- 下一篇: 深入理解malloc和free