#include<stdio.h>
#include<malloc.h>
typedef int DataType; //定义线性表的数据类型 假设为int型
typedef struct Node //定义单链表的节点类型
{
DataType data;
struct Node *next;
} Node;
Node *CreatList(DataType a[],int n)
{
Node *s = NULL;
Node *first = (Node *)malloc(sizeof(Node));
first->next = NULL; //初始化节点
for (int i = 0; i < n; i++)
{
s = (Node *)malloc(sizeof(Node));
s -> data = a[i]; //为每个数组元素建立一个节点
s -> next = first -> next; first ->next = s; //将节点s插入到头结点 之后
}
return first;
}
void PrintList(Node *first)
{
Node *p = first -> next; //工作指针p初始化
while (p != NULL)
{
printf("%d", p -> data); //输出节点的数据域 假设为int型
p = p -> next; //工作指针p后移,注意不能写作p++
}
printf("\n");
}
int Length(Node *first)
{
Node *p = first -> next; //工作指针p初始化
int count = 0; //累加器count初始化
while (p != NULL)
{
p = p -> next;
count++;
}
return count;
}
int Insert (Node *first,int i, DataType x)
{
Node *s = NULL, *p = first; //工作指针后移
int count = 0;
while ( p != NULL && count < i -1)
{
p = p -> next;
count ++;
}
if(p == NULL) { printf("位置错误,插入失败\n"); return 0; }
else {
s = (Node *)malloc(sizeof(Node));
s -> data = x;
s -> next = p ->next = s;
return 1;
}
}
int main()
{
int r[5] = {1, 2, 3, 4, 5}, i, x;
Node *first = NULL;
first = CreatList(r, 5);
printf("当前线性表的数据为:");
PrintList(first); //输出当前链表 1 2 3 4 5
Insert(first, 2, 8); //在第二个位置插入值为8的节点
printf("执行插入操作后数据为:");
PrintList(first); //输出输入后链表1 8 2 3 4 5
printf("当前单链表的长度为:%d\n", Length(first));
getchar(); getchar();
return 0;
}