单链表的使用

#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;
}
 



 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值