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]);
}