实现单链表创建、插入、删除、打印功能

本文提供了一个使用C语言实现的单链表操作示例,包括创建、插入、打印及删除单链表的方法。通过主函数进行测试,展示了完整的单链表生命周期管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// ChainSample.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>

typedef struct ChainNode{
	int num_value;
	struct ChainNode *next;
} STRU;


STRU* CreatChain(int n)
{//创建单链表,返回头指针

	STRU *head;
	STRU *p;
	STRU *q;
	int num_value;
	if (n<1)
	{
		return NULL;
	}
	head = (STRU *)malloc(sizeof(STRU));
	p=head;
	while(n)
	{
		scanf("%d",&num_value);
		if(num_value !=0)
		{
			q = (STRU *)malloc(sizeof(STRU));
			q->num_value = num_value;
			p->next = q;
			p = q;
		}
		n--;
	}
	p->next = NULL;
	return head;
}


void InsertNode(STRU *head,int num_value)
{//插入单个结点

	STRU *head_tmp = head;
	STRU *p;
	p = (STRU *)malloc(sizeof(STRU));
	p->num_value = num_value;
	p->next = head_tmp->next;
	head_tmp->next = p;

}

void PrintChain(STRU *head)
{//打印单链表

	if (!head)
	{
		printf("head is null,the chain has been deleted.\n");
		return;
	}
	STRU *tmp = head->next;
	int i = 0;
	while(tmp !=NULL)
	{
		printf("struct i=%d,num = %d\n",i,tmp->num_value);
		tmp = tmp->next;
		i++;
	}

}


void DeleteChain(STRU *head)
{//删除单链表

	STRU *tmp = head;
	STRU *p;
	while(tmp != NULL)
	{
		p = tmp;
		tmp = tmp->next;
		free(p);
	}
	head =NULL;
	PrintChain(head);
}

int _tmain(int argc, _TCHAR* argv[])
{//主函数测试

	STRU *head;
	head = CreatChain(3);
	InsertNode(head,4);
	PrintChain(head);
	DeleteChain(head);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值