我经历的华为一面、二面手撕代码题目(附答案)

一面手撕代码题目

题目描述

给一个链表和一个数,将链表分为两部分,左边部分小于x,右边部分大于或等于x,保证两部分中节点的相对顺序与之前一致。

比如:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

我的答案

#include<stdio.h>
#define L 6

typedef struct ListNode
{
    struct ListNode *next;
    int data;
}Node;

void breakNode(Node* a, Node* b)    // break b from a->b->c
{
    a->next = b->next;
}

void insertNode(Node* a, Node* b) // insert a after b
{
    if (b && b->next)
    {
        Node* temp = b->next;
        b->next = a;
        a->next = temp;
    }
    else
    {
        printf_s("cPos or cPos->next is null.");
    }
}

Node* partition(Node *head, int x)
{
    Node* temp = head;
    Node* cPos = NULL;
    int found = 0;

    while (temp && temp->next)
    {
        if (found == 0 && temp->data < x)
        {
            cPos = temp;
            found = 1;
        }
        
        if (found == 1 && temp->next && temp->next->data < x)
        {
            Node* ctemp = temp->next;
            breakNode(temp, ctemp);
            insertNode(ctemp, cPos);
            cPos = cPos->next;
        }

        if (temp->next)
        {
            temp = temp->next;
        }
        else
        {
            break;
        }
        
    }

    return head;
}

void printList(Node *input, int Length)
{
    for (int i = 0; i < Length; i++)
    {
        printf_s("%d", input->data);
        printf_s(i < Length - 1 ? "->" : "\n");
        input = input->next;
    }
}

void main()
{
    int a[L] = {1, 4, 3, 2, 5, 2};
    int x = 3;

    Node *input = (Node *)malloc(sizeof(Node));
    input->data = a[0];
    Node *head = input;
    
    for (int i = 1; i < L; i++)
    {
        Node *temp = (Node *)malloc(sizeof(Node));
        temp->data = a[i];
        head->next = temp;
        head = head->next;
    }
    head->next = NULL;

    printList(input, L);

    Node *output = partition(input, x);

    printList(output, L);
}

二面手撕代码题目

题目描述

请用随机函数float random()(返回0~1)的随机数,计算出圆周率数值。

我的答案

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

void main()
{
    srand(time(0));
    double x, y, pi;
    long int n, nt = 0;

    printf_s("Input (for example 100000): \n");    // 投针次数
    scanf_s("%ld", &n);

    for (int i = 0; i <= n; i++)
    {
        x = rand() / (double)RAND_MAX * 2.0;
        y = rand() / (double)RAND_MAX * 2.0;    // 产生(0, 2) * (0, 2)区间内的随机数        
        if (pow(x - 1.0, 2.0) + pow(y - 1.0, 2.0) <= 1.0) nt++;    //    如果随机点落在圆内
    }
    pi = 4.0 * nt / n;    // pi * r^2 / ((2r)^2) = pi / 4, so * 4.0

    printf_s("pi = %lf\n", pi);
}
posted @ 2022-08-19 19:13  天才俱乐部  阅读(299)  评论(0)    收藏  举报