最近软基的作业中,链表十分常用。于是将链表的声明和一些常用的功能封装到头文件里,以后直接引用就可以了。一下是链表的头文件:
list.h:
[cpp]
/************************************************************
* list.h *
* To implement the list. *
* by Eric Brown. *
************************************************************/
#ifndef LIST_H
#define LIST_H
typedef struct node_type
{
int data;
struct node_type *next;
}nodetype;
typedef struct list_type
{
nodetype *head;
int length;
}listtype;
/*list_init: to create a list.*/
listtype * list_create(void);
/*list_print: to print a list.*/
void list_print(listtype *list);
/*list_insert: to insert a node in a list by its address.*/
listtype * list_insert(listtype *list, int location, int data);
/*list_delete: to delete a node by its value.*/
int list_delete(listtype *list, int data);
/*list_input: to input a list.*/
listtype * list_input(listtype *list, int length);
/*list_delete_node: delete a certain node.*/
listtype * list_delete_node(listtype *list, nodetype *node);
/*list_add: to add a node.*/
nodetype * list_add(listtype *list, int data);
#endif
list.c:
[cpp]
/************************************************************
* list.c *
* by Eric Brown. *
************************************************************/
#include "list.h"
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
/*node_insert: to insert a node behind the node.*/
nodetype * node_insert(nodetype *node, int data);
/*node_delete: to delete a node from the list.*/
nodetype * node_delete(nodetype *cur, nodetype *pre);
void error(int err);
listtype * list_create(void)
{
listtype *list;
list = (listtype *)malloc(sizeof(listtype));
if (list == NULL)
error(1);
list->length = 0;
list->head = NULL;
return list;
}
nodetype * node_insert(nodetype *node, int data)
{
nodetype *temp;
temp = (nodetype *)malloc(sizeof(nodetype));
if (temp == NULL)
error(1);
temp->data = data;
temp->next = node->next;
node->next = temp;
return temp;
}
void list_print(listtype *list)
{
nodetype *temp;
if (list->length == 0 || list->head == NULL)
{
printf("This is an empty list!\n");
return ;
}
temp = list->head;
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
printf("\n\n");
}
listtype * list_input(listtype *list, int num)
{
int temp;
nodetype *cur, *next;
if (num <= 0)
error(2);
cur = list->head;
if (cur == NULL)
{
scanf("%d", &temp);
cur = (nodetype *)malloc(sizeof(nodetype));
cur->data = temp;
num--;
list->length = 1;
list->head = cur;
} else{
while (cur->next != NULL)
cur = cur->next;
}
while (num--)
{
scanf("%d", &temp);
next = (nodetype *)malloc(sizeof(nodetype));
next->data = temp;
cur->next = next;
cur = next;
list->length++;
}
cur->next = NULL;
return list;
}
listtype * list_insert(listtype *list, int location, int data)
{
nodetype *temp, *cur;