내 가 겪 은 화 웨 이의 한 면, 두 손 으로 코드 를 뜯 는 문제 (정 답 첨부)

코드 문제
제목 설명
하나의 링크 와 하나의 수 를 주 고 링크 를 두 부분 으로 나 누 며 왼쪽 부분 은 x 보다 작고 오른쪽 부분 은 x 보다 크 거나 같 으 며 두 부분 에서 노드 의 상대 적 인 순서 가 이전 과 일치 하도록 확보한다.
예 를 들 어: 입력: head = 1 - > 4 - > 3 - > 2 - > 5 - > 2, x = 3 출력: 1 - > 2 - > 2 - > 4 - > 3 - > 5
나의 답
#include
#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 ? "->" : "
"
); 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
#include
#include
#include

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

	printf_s("Input (for example 100000): 
"
); // 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
"
, pi); }

좋은 웹페이지 즐겨찾기