笔试编程题总结

本文总结了六道常见的C/C++编程笔试题目,包括计算字符串长度、判断链表环、复制字符串、交换数值、遍历数组以及利用指针对数组进行求和与排序操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、键盘输入一个字符串,编写代码获取字符串的长度并输出,要求使用字符指针实现。


#include <iostream>
using namespace std;

int main() {
    char str[100]={0};
    cin.getline(str,sizeof(str));
    int  len=0;
    char *p =str;
    while (*p!='\0')
    {
        len ++;
        p++;

    }
    cout<<len<<endl;
    return 0;
}

2、 判断链表中是否有环

#include <stdbool.h>
/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
 */
bool hasCycle(struct ListNode* head ) {
    // write code here
    if(head==NULL||head->next==NULL)
{
  return NULL;
}    
struct ListNode*slow=head->next,*fast=head->next->next;
while(fast!=NULL&&fast->next!=NULL)
{
 if(fast==slow)
 return true;
 slow=slow->next;
 fast=fast->next->next;
}
return false;
}

3、复制部分字符串


#include <iostream>
using namespace std;

int main() {
    char str[30]={0};
    cin.getline(str,sizeof(str));
     
     int m;
     cin >> m;
     
     char* newStr=str+m-1;
     for (* newStr; * newStr !='\0';newStr++)
     {
         cout<<*newStr;

     }
      return 0;

}

4、编写一个函数实现两个数的交换

#include <iostream>
using namespace std;
void swap(int *a,int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
   
}
int main() {
    int a,b;
   cin >> a >> b;
    swap(&a,&b);
    cout << a << ' ' << b << endl;
    return 0;

}

5、利用指针遍历数组

#include <iostream>
using namespace std;

int main() {
   int arr[6]={0};
   int *p=arr;
   int i=0;
   int len = sizeof(arr) / sizeof(int);
  for(i=0;i<len;i++)
  {
      cin>>arr[i];
  }
 for( p;p<arr+len;p++)
      {
      cout<< *p<<' ';
   } 
   return 0;
}

6、牛牛学习了指针相关的知识,想实现一个 int cal(int *array,int n) 的函数求出长度为 n 的数组的和。

#include <stdio.h>
int cal(int *array,int n);
int main() {
     int n=0,i=0;
     scanf("%d",&n);
     int arr[n];
     for(i=0;i<n;i++)
      {
        scanf("%d",&arr[i]);
      }          
     printf("%d",cal(arr,n));
    return 0;
}
int cal(int *array,int n)
{
    int sum=0;
    int i=0;
    for(i=0;i<n;i++)
    {
      sum+=*(array+i);
    }
    return sum;

}

牛牛试图给一个长度为 n 整数数组排序,即实现一个 void sort(int *array,int n);


#include <stdio.h>
void sort(int *array,int n)
{
  int i,j=0;
  for(i=0;i<n-1;i++)
  {
      for(j=0;j<n-i-1;j++)
      {
          if(array[j+1]<array[j])
          {
             int temp=array[j];
             array[j]=array[j+1];
             array[j+1]=temp;
          }
      }

  }

  for(i=0;i<n;i++)
  {
     printf("%d ",array[i]);

  }
}
int main() {
    int n,i=0;
    int arr[100];
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
     scanf("%d",&arr[i]);
    }
    sort (arr,n);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值