数据结构:单链表创建增加节点、求表长、查找并定位链表节点数据、插入链表节点、删除链表节点,最后打印出来;可直接复制代码运行并检验

数据结构结构中单链表创建增加节点、求表长、查找并定位链表节点数据、插入链表节点、删除链表节点,最后打印出来;可直接复制代码运行并检验;
注意:这里的代码编译环境是vs2013,如果你在其他的编译环境可以先把"scanf_s"改成"scanf"

#include"stdio.h"
#include"stdlib.h"

typedef struct node * pointer;

typedef	struct node{
	char data;
	pointer next;
}list;
//创建增加节点
pointer creat()
{
	pointer head, rear, s;
	char a;
	head = (struct node*)malloc(sizeof(struct node));
	rear = head;
	while (scanf_s("%c", &a),a != '$'){
		s = (struct node*)malloc(sizeof(struct node));
		s->data = a;
		rear->next = s;
		rear = s;
	}
	rear->next= NULL;
	return head;
}

//求表长
int length(pointer head)
{
	pointer p;
	int n = 0;
	p = head->next;
	while (p != NULL){
		p = p->next;
		n++;
	}
	return n;
}

//查找并定位
pointer locate(pointer head, char c,int * f)
{
	pointer p;
	p = head->next;
	while ( p != NULL){
		(*f)++;
		if (p->data == c) break;
		p = p->next;
	}
	if (*f <= 0) p=NULL;
	return p;
}

//插入
void insert(pointer head, char c, int i)
{
	pointer p, s;
	int j = 1;
	if (i <= 0)	return;
	s = (struct node *)malloc(sizeof(struct node));
	s->data = c;
	p = head->next;
	while (j < i-1 && p->next != NULL){
		p = p->next;
		j++;
	}
	s->next = p->next;
	p->next = s;
	printf("hello\n");
	return;
}

//删除
void del(pointer head, int i)
{
	pointer s, p;
	int j = 1;
	p = head->next;
	if (i <= 0) return;
	while (j < i - 1 && p != NULL){
		j++;
		p = p->next;
	}
	s = p->next;
	p->next = s->next;
	free(s);
	return;
}

void main()
{
	pointer head,p,find;
	int l,f=0;
	head=creat();//建表
	p = head->next;
	//打印出表数据
	do{
		printf("%c", p->data);
		p = p->next;
	}while(p!=NULL);
	printf("\n");
	p = head->next;
	//求表长
	l = length(head);
	printf("表长:%d\n", l);
	//定位查找
	find = locate(head, 'h',&f);
	if (find != NULL)
	{
		printf("查找字符%c,定位在第%d个\n", find->data, f);
	}
	else
	{
		printf("查找失败!\n");
	}
	//插入并重新打印
	insert(head, '*', 3);
	printf("插入后新链表数据:\n");
	do{
		printf("%c", p->data);
		p = p->next;
	} while (p != NULL);
	printf("\n");
	p = head->next;
	//删除
	del(head, 4);
	printf("删除后新链表数据:\n");
	do{
		printf("%c", p->data);
		p = p->next;
	} while (p != NULL);
	printf("\n");
	p = head->next;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值