Main déchirant le problème de code
Description du titre
Étant donné une liste chaînée et un nombre, divisez la liste chaînée en deux parties, la partie gauche est inférieure à x et la partie droite est supérieure ou égale à x, pour vous assurer que l'ordre relatif des nœuds dans les deux parties est la même chose qu'avant.
比如 :
Entrée: tête = 1-> 4-> 3-> 2-> 5-> 2, x = 3
Sortie: 1-> 2-> 2-> 4-> 3-> 5
ma réponse
#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);
}
Problème de code déchiqueté recto-verso
Description du titre
Veuillez utiliser la fonction aléatoire float random () (renvoyant 0 ~ 1) pour calculer la valeur de Pi.
ma réponse
#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);
}