7.9数据结构

发布于:2024-07-13 ⋅ 阅读:(154) ⋅ 点赞:(0)

思维导图

作业

doubleloop.h

#ifndef __DOUBLELOOP_H__
#define __DOUBLELOOP_H__

#include <stdio.h>
#include <stdlib.h>

typedef int datatype;
typedef struct node
{
	union
	{
		int len;
		datatype data;
	};
	struct node *pri;//前驱指针
	struct node *next;//后继指针
}node,*node_p;
 
//创建链表
node_p list_create();
//创建节点
node_p node_create(node_p H,datatype data);
//判空
int node_empty(node_p H);
//尾插
int tail_input(node_p H,datatype data);
//遍历
int node_show(node_p H);
//尾删
int del_tail(node_p H);
//销毁
int node_free(node_p H);
 
#endif

doubleloop.c

#include "doubleloop.h"

//创建链表
node_p list_create()
{
	node_p H=(node_p)malloc(sizeof(node));
    if(NULL==H)
    {
        printf("---创建链表失败---\n");
        return NULL;
    }
    H->len=0;
	H->pri=H;
	H->next=H;
    printf("---创建链表成功---\n");
    return H;
}
//创建节点
node_p node_create(node_p H,datatype data)
{
	node_p new=(node_p)malloc(sizeof(node));
	if(new==NULL)
	{
		printf("---创建节点失败---\n");
		return 	NULL;
	}
	new->data=data;
	new->pri=H;
	new->next=H;
	return new;
}
//判空
int node_empty(node_p H)
{
	if(H==NULL)
  	{
  	    printf("---入参为空,请检查---\n");
    	return -1;
  	}
  	return H->next==H;
}

//尾插
int tail_input(node_p H,datatype data)
{
	if(H==NULL)
	{
		printf("---入参为空,请检查---\n");
		return 0;
	}
	node_p new=node_create(H,data);
	node_p p=H->next;
	while(p->next!=H)
	{
		p=p->next;
	}
	new->pri=p;
	p->next=new;

	H->len++;
	return 1;
}
//遍历
int node_show(node_p H)
{
	if(H==NULL||node_empty(H))
	{
		printf("---输出有误---\n");
		return 0;
	}
	node_p p=H->next;
	printf("链表为:H->");
	while(p!=H)
	{
		printf("%d->",p->data);
		p=p->next;
	}
	printf("H\n");
	return 1;
}

//尾删
int del_tail(node_p H)
{
	if(H==NULL||node_empty(H))
	{
		printf("---尾删失败,请检查---\n");
		return 0;
	}
	node_p p=H;//H会找到需要位置的前一个节点
	for(int i=0;i<H->len-1;i++)//len和pos是一个意思,是位置而不是下标,-1为了移动到最后一个的前一个节点停止
	{
		p=p->next;
	}
	node_p q=p->next;//定义出最后一个节点,方便释放空间
	
	p->next=H;//将倒数第二个节点指向NULL,一根线
	
	free(q);
	q=NULL;
	H->len--;
	return 1;
}

//销毁
int node_free(node_p H)
{
	if(H==NULL)
	{
		printf("---链表销毁有误,请检查---\n");
		return 0;
	}
	while(H->next!=H)
	{
		del_tail(H);
	}
	free(H);
	H=NULL;
	printf("---链表销毁成功---\n");
	return 1;
}


网站公告

今日签到

点亮在社区的每一天
去签到