C语言数据结构——单链表的构建,增删查找

本篇是用C语言来实现,数据结构中的链式存储及其基础操作。

  • 链表
    其结构体成员:内容info,下一个节点的指针。

C代码实现如下


#include <stdio.h>

typedef int DataType;

struct node
{
	DataType info;
	struct node *next;
};

typedef struct node *Node;

//创建空链表 
Node CreateNULLlink()
{
	Node head=(Node )malloc(sizeof(struct node));
	if(head!=NULL)
	{
		head->info=0;
		head->next=NULL;
		return head;
	}
	return NULL;
}

//判断链表是否为空 
int IsNULLlink(Node head)
{
	return (head->next==NULL);
}

//输出链表
void Printlink(Node head)
{
	Node temp=head->next;
	while(temp!=NULL)
	{
		printf("%d ", temp->info);
		temp=temp->next;
	}
	printf("\n");
} 

//带头节点的尾插法 
int InsertLink(Node head, DataType x)
{
	Node p, temp=(Node )malloc(sizeof(struct node));
	if(head==NULL || temp==NULL) return 0;
	
	p=head->next;
	temp->info=x;
	temp->next=NULL;

	if(p==NULL)
	{
		head->next=temp;
		return 1;   //记得返回值 
	}
	
	while(p->next!=NULL)
	{
		p=p->next;
	}
	p->next=temp;

	
	return 1;
}

//头插法
int InsertPre(Node head, DataType x)
{
	Node p, temp=(Node )malloc(sizeof(struct node));
	if(temp==NULL) return 0;
	
	temp->info=x;
	temp->next=head->next;
	head->next=temp;
	return 1;
} 

//查找, 返回第一个值为x的节点存储位置 
Node LocateNode(Node head, DataType x)
{
	Node p;
	if(head==NULL) return 0;
	p=head->next;
	while(p!=NULL)
	{
		if(p->info==x) return p;
		p=p->next;
	}

}

//定位p的前驱节点并删除p
Node DelNode(Node head, Node p)
{
	Node temp, q=head;
	if(head==NULL || head->next==NULL) return NULL;
	if(q->next==p)
	{
		printf("该节点没有前驱节点\n");
	}
	while(q!=NULL)
	{
		if(q->next->next==p)
		{
			temp=q->next;
			q->next=p;
			return temp;
		}
	}
}


int main()
{
	Node head, temp;
	int n, t;
	DataType x;
	head=CreateNULLlink();
	temp=head->next;
	
	printf("请输入节点的数目: "); 
	scanf("%d", &n);
	printf("\n请输入节点内容: ");
	
	for(int i=0; i<n; i++)
	{
		scanf("%d", &x);
		InsertLink(head, x);
	}
//	printf("%d", x);
//	Printlink(head);
 
	printf("\n头插法,请输入要插入的内容: "); 
	scanf("%d", &x);
	InsertPre(head, x);
	
	printf("\n插入后的链表:");
	Printlink(head);
	
	printf("\n请输入要删除内容的前驱: ");
	scanf("%d", &x);
	temp=LocateNode(head, x); 
	DelNode(head, temp);
	
	printf("\n删除后的链表:");
	Printlink(head);	
	
	return 0;
}

按照提示输入运行即可
运行结果如下
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值