只实现了几个简单的操作。在Linux内核中链表的使用非常多,不过使用方法与本例完全不一样。后续有时间再详述。
ChainNode.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DATA_LEN 128
#define CN_TRUE 0
#define CN_FALSE 1
#define CN_ERROR -1
typedef struct ChainNode ChainNode;
struct ChainNode {
char data[MAX_DATA_LEN+1];
ChainNode *next;
};
static int get_chain_len(ChainNode *head)
{
int len = 0;
ChainNode *node;
node = head;
while(node) {
len++;
node = node->next;
}
return len;
}
/*
* Create a new node, and append it to the end of chain.
*/
static int chain_append(ChainNode *head, char *content, int content_len)
{
ChainNode *node;
ChainNode *new_node;
if(NULL == head || NULL == content || content_len < 1 || content_len > MAX_DATA_LEN)
return CN_ERROR;
new_node = (ChainNode *)malloc(sizeof(ChainNode));
if(NULL == new_node)
return CN_ERROR;
strncpy(new_node->data, content, content_len);
new_node->next = NULL;
node = head;
while(node->next)
node = node->next;
node->next = new_node;
return CN_TRUE;
}
/*
* Destroy the chain except the head node
*/
static void chain_destroy(ChainNode *head)
{
ChainNode *node;
ChainNode *next;
int i = 0;
printf("There are %d nodes in chain.\n", get_chain_len(head));
node = head;
do {
next = (node->next)->next;
free(node->next);
i++;
node->next = next;
} while(node->next);
printf("Call free %d times.\n", i);
}
/*
* index is start from 1. If index is valid, the data will be copy to ChainNode *target.
*/
static int chain_find_node_by_index(ChainNode *head, ChainNode *target, int index)
{
ChainNode *node;
if(NULL == head || NULL == target || index < 1 || index > get_chain_len(head))
return CN_ERROR;
node = head;
while(--index > 0 && node) {
node = node->next;
}
if(index != 0)
return CN_ERROR;
memcpy(target->data, node->data, MAX_DATA_LEN);
return CN_TRUE;
}
static void chain_output(ChainNode *head)
{
int i = 1;
ChainNode *node;
node = head;
while(node) {
printf("%d:%s\n", i++, node->data);
node = node->next;
}
}
int main()
{
ChainNode head;
ChainNode theThirdNode;
char str1[] = "The second element";
char str2[] = "The third element";
char str3[] = "The fourth element";
/* Create the head node */
memset(&head, 0, sizeof(ChainNode));
strcpy(head.data, "The first element");
head.next = NULL;
/* Append several elements */
chain_append(&head, str1, strlen(str1));
chain_append(&head, str2, strlen(str2));
chain_append(&head, str3, strlen(str3));
/* Output */
chain_output(&head);
/* Find the element */
memset(&theThirdNode, 0, sizeof(ChainNode));
chain_find_node_by_index(&head, &theThirdNode, 3);
printf("Find 3:%s\n", theThirdNode.data);
/* Destroy */
chain_destroy(&head);
return 0;
}