728x90
https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem
두 연결 리스트의 연결지점을 찾는 문제
마지막에 return tmp1->data 또는 return tmp2->data 둘다 된다. (어차피 합병 포인트는 같으니까)
int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
SinglyLinkedListNode *temp1=head1;
SinglyLinkedListNode *temp2=head2;
while(temp1!=temp2){
if(temp1->next==NULL){
temp1=head2;
}
else {
temp1=temp1->next;
}
if(temp2->next==NULL){
temp2=head1;
}
else{
temp2=temp2->next;
}
}
return temp2->data;
}
△코드 작성 부분
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
typedef struct SinglyLinkedListNode SinglyLinkedListNode;
typedef struct SinglyLinkedList SinglyLinkedList;
struct SinglyLinkedListNode {
int data;
SinglyLinkedListNode* next;
};
struct SinglyLinkedList {
SinglyLinkedListNode* head;
SinglyLinkedListNode* tail;
};
SinglyLinkedListNode* create_singly_linked_list_node(int node_data) {
SinglyLinkedListNode* node = malloc(sizeof(SinglyLinkedListNode));
node->data = node_data;
node->next = NULL;
return node;
}
void insert_node_into_singly_linked_list(SinglyLinkedList** singly_linked_list, int node_data) {
SinglyLinkedListNode* node = create_singly_linked_list_node(node_data);
if (!(*singly_linked_list)->head) {
(*singly_linked_list)->head = node;
} else {
(*singly_linked_list)->tail->next = node;
}
(*singly_linked_list)->tail = node;
}
void print_singly_linked_list(SinglyLinkedListNode* node, char* sep, FILE* fptr) {
while (node) {
fprintf(fptr, "%d", node->data);
node = node->next;
if (node) {
fprintf(fptr, "%s", sep);
}
}
}
void free_singly_linked_list(SinglyLinkedListNode* node) {
while (node) {
SinglyLinkedListNode* temp = node;
node = node->next;
free(temp);
}
}
int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
SinglyLinkedListNode *temp1=head1;
SinglyLinkedListNode *temp2=head2;
while(temp1!=temp2){
if(temp1->next==NULL){
temp1=head2;
}
else {
temp1=temp1->next;
}
if(temp2->next==NULL){
temp2=head1;
}
else{
temp2=temp2->next;
}
}
return temp2->data;
}
int main()
SMALL
'Programming > C C++' 카테고리의 다른 글
Print the Elements of a Linked List (0) | 2020.08.16 |
---|---|
Kangaroo (0) | 2020.08.16 |
Apple and Orange (0) | 2020.08.07 |
Compare two linked lists (0) | 2020.08.02 |
Grading Students (0) | 2020.08.01 |