建立一个工程,在其中添加 list.h 头文件,list.cpp源文件和main.cpp源文件。
头文件list.h中进行数据类型抽象(ADT),声明了一个结构体和对应的操作,代码如下:
#ifndef _LIST_H_
#define _LIST_H_
typedef struct list
{
int data;
struct list *next;
}List;
/*函数声明*/
List* InitList();
List* InitNode(int d);
void RemoveList(List *head);
List *InsertList(List *head, int i,int x);
List *DeleteNode(List *head,int i);
void DisplayList(List *head);
void GetListLength(List *head);
#endif // !_LIST_H_
再实现对应的操作,即list.cpp,代码如下:
#include<stdlib.h>
#include<stdio.h>
#include<assert.h>
#include"list.h"
/*初始化链表*/
List *InitList()
{
List *head;
head = (List *)malloc(sizeof(List));
assert(head != NULL);
head->next = NULL;
return head;
}
/*新建节点*/
List* InitNode(int d)
{
List *p;
p = (List*)malloc(sizeof(List));
p->data = d;
p->next = NULL;
assert(p != NULL); //这里是一个断言
return p;
}
/*销毁链表*/
void RemoveList(List *head)
{
List *p,*temp;
p = head->next;
while (head != NULL)
{
p = head;
head = head->next;
delete p;
}
printf("链表已销毁\n");
}
/*插入节点*/
List *InsertList(List *head,int i,int x) //i为链表第i个结点,x为要插入的数据
{
List *p,*q;
int j = 0;
q = head->next;
while (q != NULL&&j<i-1)
{
q = q->next;
++j;
}
if (q == NULL || j > i - 1)
{
printf("位置不合法\n");
}
else
{
p = (List*)malloc(sizeof(List));
p->data = x;
p->next = q->next;
q->next = p;
}
return head;
}
/*删除链表中的节点*/
List *DeleteNode(List *head, int i) //i为链表第i个结点
{
if (head == NULL)
printf("Empty List!\n");
List *p = head->next;
int j = 0;
while (p != NULL&&j<i - 1)
{
p = p->next;
++j;
}
if (p == NULL || j > i - 1)
{
printf("位置不合法\n");
}
else
{
List *temp;
temp = p->next;
p->next = temp->next;
delete temp;
}
return head;
}
/*打印链表*/
void DisplayList(List *head)
{
List *p;
p = head->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
/*获取链表长度*/
void GetListLength(List *head)
{
List *p;
int j = 0;
p = head->next; //头节点没有数据
while (p != NULL)
{
++j;
p = p->next;
}
printf("链表的当前长度为:%d\n", j);
}
最后就是在main函数里测试了,代码如下:
#include<stdio.h>
#include"list.h"
int main(void)
{
List *head,*tail,*p; //声明链表的头尾结点
int a[] = { 1,3,6,0,5,7,9 }; //定义一个数组,将其元素作为结点的数据
tail = head = InitList(); //新建一个带头节点的链表
for (int i = 0; i < 7; i++)
{
p = InitNode(a[i]);
tail->next = p; //尾插法
tail = p;
}
DisplayList(head);
InsertList(head,3,25); //在3号位插入25这个元素
DisplayList(head);
DeleteNode(head,2); //删除2号位的元素
DisplayList(head);
GetListLength(head); //打印链表当前长度
RemoveList(head); //销毁链表
return 0;
}
写得比较拙劣,还请多多指教