1.编写函数计算滑动窗口的最大值,函数给定一个数组和滑动窗口的大小,返回所有滑动窗口里数值的最大值。例如
通过参数给定数组及滑动窗口的大小:[2,3,4,2,6,2,5,1],3 => [4,4,6,6,6,5]
#include <stdio.h>
#include <stdlib.h>
int func(int *arr,int n,int size) {
int times=size-n+1;
int *final=(int *)malloc(sizeof(int)*times);
for(int i=0; i<times; i++) {
int max=0;
for(int j=i; j<n+i; j++)
if(arr[j]>max)
max=arr[j];
final[i]=max;
}
for(int i=0; i<times; i++)
printf("%d ",final[i]);
}
int main() {
int arr[]= {2,3,4,2,6,2,5,1};
int size=sizeof(arr)/sizeof(int);
func(arr,3,size);
}
2.编写函数删除链表中重复的节点。在一个已经排序的整数链表中,删除该链表中结点相同的重复节点,重复节点都不保留,返回处理后的链表。例如:
通过参数给定链表:1->2->3->3->4->4->5
返回链表1->2->5
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int key;
struct node *next;
} node;
struct node *deletesame(struct node *head) {
if(head==NULL)
return head;
struct node *p=head,*q=head->next;
while(q!=NULL)
if(p->key==q->key) {
p->next=q->next;
struct node *del = q;
free(del);
q=p->next;
} else {
p=q;
q=q->next;
}
return head;
}
3.编写递归函数判断二叉树是否对称。二叉树对称是指二叉树的结构和结点值左右对称。给定一棵非空,节点值为整数的二叉树,判断二叉树是否为对称二叉树
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct treenode {
int val;
struct treenode *left,*right;
} treenode;
bool issymmetric1(struct treenode *lchild,struct treenode *rchild) {
if(lchild==NULL&&rchild==NULL)
return true;
if(lchild==NULL||rchild==NULL)
return false;
if(lchild->val!=rchild->val)
return false;
return issymmetric1(lchild->left,rchild->right)&&issymmetric1(lchild->right,rchild->left);
}
bool issymmetric(struct treenode *root) {
if(root==NULL)
return true;
return issymmetric1(root->left,root->right);
}
bool issymmetric2(struct treenode *root) {
if(root==NULL)
return true;
struct treenode** queue=(struct treenode **)malloc(sizeof(struct treenode*)*100);
int front=-1,rear=-1;
queue[++rear]=root->left;
queue[++rear]=root->right;
while(front!=rear) {
struct treenode *p=queue[++front];
struct treenode *q=queue[++front];
if(p==NULL&&q==NULL)
continue;
if(p==NULL||q==NULL)
return false;
if(p->val!=q->val)
return false;
queue[++rear]=p->left;
queue[++rear]=q->right;
queue[++rear]=p->right;
queue[++rear]=q->left;
}
return true;
}
4.编写函数求子数组。给定一个整型数组,返回具有最大和的连续子数组,若有多个子数组具有相同最大和,则返回任意一个即可
#include <stdio.h>
#include <stdlib.h>
int func(int *arr,int n,int size,int flag) {
int times=size-n+1;
int max=0;
int *dp=(int *)malloc(sizeof(int)*size);
init(dp,size);
for(int i=0; i<times; i++) {
int sum=0;
for(int j=i; j<n+i; j++)
sum+=arr[j];
if(sum>max) {
max=sum;
init(dp,size);
for(int j=i; j<n+i; j++)
dp[j]=1;
}
}
if(flag==1) {
for(int i=0; i<size; i++)
if(dp[i]==1)
printf("%d ",arr[i]);
}
else
return max;
}
void init(int *arr,int size) {
for(int i=0; i<size; i++)
arr[i]=0;
}
void getmax(int *arr,int size) {
int max=0,flag=0;
for(int i=0; i<size; i++)
if(max<func(arr,i,size,0)) {
max=func(arr,i,size,0);
flag=i;
}
func(arr,flag,size,1);
}
int main() {
int arr[]= {-2,1,-3,4,-1,2,1,-5,4};
int size=sizeof(arr)/sizeof(int);
getmax(arr,size);
}