数据结构第4天

功能函数:链式栈(头插头删)

#include "./03_binary.h"

LinkHouse* create_linkhouse()
{
	LinkHouse* head=(LinkHouse*)malloc(sizeof(LinkHouse));
	if(head==NULL){
		printf("创建头结点失败\n");
		return NULL;
	}
	memset(head,0,sizeof(LinkHouse));
	return head;
}


void insert_linkhouse_before(LinkHouse* head,datatype data)
{
	LinkHouse* temp=(LinkHouse*)malloc(sizeof(LinkHouse));
	temp->text.data=data;
	
	temp->next=head->next;
	head->next=temp;
	head->text.len++;
	return;
}

void delete_linkhouse_before(LinkHouse* head)
{
    if(head->next==NULL){
        printf("链式栈为空\n");
        return;
    }
	LinkHouse* temp=head->next;
	head->next=head->next->next;
	free(temp);
	head->text.len--;
	return;
}

void travel_linkhouse(LinkHouse* head)
{
	LinkHouse* p=head;
	while(p->next!=NULL){
		p=p->next;
		printf("%d ",p->text.data);
	}
	printf("len:%d\n",head->text.len);
	putchar(10);
	return;
}

栈的进制转换,将十进制转换成二进制。

链栈实现思路:循环把余数入栈循环出栈,直到栈空为址

void compter_binary(LinkHouse* head,int num)
{
	if(num<0){
		printf("数据不合法\n");
		return;
	}

	int rem;
	while(num!=0){ 
		rem=num%2; //算出余数
		num=num/2; //将数字除2
		insert_linkhouse_before(head,rem);
	}
	travel_linkhouse(head);
	return;
}

(()(()(())(()))

(()())

)(

()())(()

判断括号是否匹配:

提示:使用链式栈实现:遇到(,将(入栈。遇到),将栈中的数据出栈。

void isCouple(LinkHouse* head,char* str)
{
	int len=strlen(str);
	int flag=0;
	datatype data;
	for(int i=0;i<len;i++){
		if('('==str[i]){ //入栈
			insert_linkhouse_before(head,str[i]);
		}else if(')'==str[i]){ //出栈
			if(data=delete_linkhouse_before(head)==1){			
				flag=1; //出栈到栈空无法判断是否匹配
				break;
			}
		}
	}
        //head->next!=NULL判断左括号多了
        //flag==1 判断右括号多了
		if( head->next!=NULL || flag==1) { 
			printf("括号不匹配\n");
		}else{
			printf("括号匹配\n");
		}
	return;
}

主函数

int main(int argc, const char *argv[])
{
	LinkHouse* head=create_linkhouse();

//	compter_binary(head,5);	
	char str[10]="()()";
	isCouple(head,str);	

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值