高级语言讲义2021计专(仅高级语言部分)

本文介绍了四个C语言编程示例:统计字符串中字符出现次数(考虑连续字符),交换单链表节点位置,检测二叉树中是否存在平衡节点,以及生成满足特定条件的子集。
摘要由CSDN通过智能技术生成

1.给定字符串,统计各个字符出现的次数,连续出现算一次,如ABCBBBA,B为两次

#include <stdio.h>

void count(char *s) {
	int hash[256];
	for(int i=0; i<=255; i++)
		hash[i]=0;
	int i=0;
	while(s[i]!='\0') {
		if(i>0&&s[i]==s[i-1]) {
			i++;
			continue;
		}
		hash[s[i]]++;
		i++;
	}
	for(int i=0; i<=255; i++)
		if(hash[i]!=0)
			printf("%c:%d\n",i,hash[i]);
}

int main(){
	char s[100]="abcbbd";
	count(s);
}

2.两两互换单链表中结点的位置

#include <stdio.h>

typedef struct node {
	int data;
	struct node *next;
} node;

struct node *reverse01(struct node *head) {
	if(head==NULL||head->next==NULL)
		return head;
	struct node *p=head;
	head=head->next;
	p->next=head->next;
	head->next=p;
	p->next=reverse(p->next);
	return head;
}

struct node *reverse02(struct node *head) {
	struct node *dummyhead=(struct node *)malloc(sizeof(struct node));
	dummyhead->next=head;
	struct node *pre=dummyhead;
	while(pre->next!=NULL&&pre->next->next!=NULL) {
		struct node *p=pre->next;
		struct node *q=pre->next->next;
		p->next=q->next;
		q->next=p;
		pre->next=q;
		pre=q;
	}
	return dummyhead->next;
}

3.检测二叉树中是否有平衡结点:左右子树数据值相等则为平衡节点

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

typedef struct treenode {
	int val;
	struct treenode *left,*right;
} treenode;

int postorder(struct treenode *root,bool *have) {
	if(root==NULL)
		return NULL;
	if(root->left==NULL&&root->right==NULL)
		return root->val;
	int leftsum=postorder(root->left,have);
	int rightsum=postorder(root->right,have);
	if(leftsum==rightsum)
		*have=true;
	return leftsum+rightsum+root->val;
}

bool balance(struct treenode* root) {
	bool have=false;
	postorder(root,&have);
	return have;
}

4.输出符合以下条件的子集(难)

子集元素两两相异

子集元素任意大元素%小元素=0

符合以上条件最多元素的子集

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

void sort_a(int a[], int n) {
	for(int i=0; i < n; i++)
		for(int j=0; j<n-1; j++)
			if(a[j]>a[j+1]) {
				int temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
}

void num_max(int a[], int n) {
	int max=0,count,flag=0;
	int *b=(int *)malloc(sizeof(int)*n);
	int *maxnum=(int *)malloc(sizeof(int)*n);
	for(int i=0; i<n; i++) {
		b[i]=0;
		maxnum[i]=0;
	}
	sort_a(a,n);
	
	for(int i=0; i < 1<<n; i++) {
		count=0;
		for(int j=0; j < n; j++) 
			if(i & (1 << j)) 
				b[count++] = a[j];
				
		if(count>max) {
			flag = 1;
			for(int j=1; j < count; j++) 
				if(b[j] == b[j-1] || b[j]%b[j-1]!=0) {
					flag = 0;
					break;
				}
			if(flag==1) {
				for(int j=0; j<count; j++) 
					maxnum[j] = b[j];
				max = count;
			}
		}
	}
	for(int i=0; i<max; i++) 
		printf("%d   ",maxnum[i]);
}

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值