Hand tearing up the code problem
Title description
Given a linked list and a number, divide the linked list into two parts, the left part is less than x, and the right part is greater than or equal to x, to ensure that the relative order of the nodes in the two parts is the same as before.
比如:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
my answer
#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);
}
Two-sided shredded code problem
Title description
Please use the random function float random() (returns 0~1) to calculate the number of pi.
my answer
#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);
}