本博客记录了如何使用C语言去实现数据结构中的链表,下面将展示其代码的具体实现。
其中还有向链表插入节点、删除节点、遍历链表的相关方法。
代码中写了大量注释,便于大家理解
LinkedList.c
#include
#include "LinkedList.h"
Node*
Insert(Node*h, Node *p )
{
if (h == NULL)
{
return p;
}
if (p == NULL)
{
return h;
}
if (p->data < h->data)
{
p->next = h;
return p;
}
else
{
h->next = Insert(h->next ,p);
return h;
}
}
void print_list(Node *h)
{
while (h)
{
printf("%d ", h->data);
h = h->next;
}
}
// 逆序(从最后一个结点开始)打印一个单链表
void p(Node *h)
{
if (h == NULL)
{
return ;
}
//1. 先逆序打印后面那个链表
p(h->next);
//2. 再打印第一个结点
printf("%d ", h->data);
}
int sum(Node* h)
{
if (h == NULL)
{
return 0;
}
else
{
return h->data + sum(h->next);
}
}
Node* delete_x(Node*h , DataType x)
{
if (h == NULL)
{
return NULL;
}
if (h->data != x)
{
h->next = delete_x(h->next, x) ;
return h;
}
else //h->data == x
{
// 先删除结点 h
Node *p = h->next;
h->next = NULL;
free(h);
//再删除后面那个链表上值为x的结点
//整个完成后,链表的第一个结点,应该为后面那个链表
//的第一个结点
return delete_x(p, x);
}
}
LinkedList.h
#ifndef __LINKEDLIST_H__
#define __LINKEDLIST_H__
typedef int DataType;
// "数据结点"
typedef struct Node
{
DataType data; // "数据域":保存数据元素的
struct Node* next; // "指针域":保存下一个数据元素的地址
}Node;
Node*
Insert(Node*h, Node *p );
void print_list(Node *h);
Node*
delete_x(Node*h , DataType x);
#endif
链表的插入、删除节点测试用例
main.c
#include#include #include "LinkedList.h" int main() { Node *h = NULL; //指向链表的第一个结点 int d; while (1) { scanf("%d", &d); if (d == 0) { break; } //1.申请一个结点,保存数据d Node *p = (Node*)malloc(sizeof(Node)) ; p->data = d; p->next = NULL; // 2. 把p插入到h指向的升序链表中去 h = Insert(h, p) ; } print_list(h); int x; scanf("%d", &x); h = delete_x(h, x); print_list(h); return 0; }



