// 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;
}
实现单链表创建、插入、删除、打印功能
最新推荐文章于 2021-02-10 15:28:30 发布