---
# System prepended metadata

title: 12695 - Card Magic (Simplified)
tags: [linked list]

---

# 12695 - Card Magic (Simplified)
>author: Utin
###### tags: `linked list`
---

## Brief
See the code below

## Solution 0

```c=
#ifndef __FUNCTION_H__
#define __FUNCTION_H__

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

typedef struct _Node{
    int size;
    int* data;
    struct _Node* next;
} Node;

extern Node* ReadOneList();
extern void PrintList(Node*);
extern void Merge(Node*, int, int);
extern void Cut(Node*, int, int);

Node* CreateNode(int size){
    Node* n = (Node*) malloc( sizeof(Node) );
    n->size = size;
    n->data = (int*) malloc( sizeof(int) * size );
    n->next = NULL;
    return n;
}

Node* ReadOneList(){
    int Ni;
    scanf("%d:", &Ni);
    Node* new_node = CreateNode(Ni);
    for (int i=0; i<new_node->size; i++){
        scanf(" %d", &(new_node->data[i]) );
    }
    return new_node;
}

void PrintList(Node* dummy_head){
    Node* cur = dummy_head->next;
    while (cur != NULL) {
        printf("%d", cur->data[0]);
        for(int i=1; i<cur->size; i++){
            printf(" %d", cur->data[i]);
        }
        printf("\n");
        cur = cur->next;
    }
}
void Merge(Node* dummy_head, int back, int front){

	// search
	Node* f, * b, * pre_b, * curr = dummy_head;
	for (int i = 0; i <= back || i <= front; i++) {
		if (i == back-1) pre_b = curr;
		if (i == back) b = curr;
		if (i == front) f = curr;
		curr = curr->next;
	}

	// merge data
	int* tmp = (int*) malloc(sizeof(int) * (b->size + f->size));
	for (int i = 0; i < f->size; i++) {
		tmp[i] = f->data[i];
	}
	for (int i = f->size; i < f->size + b->size; i++) {
		tmp[i] = b->data[i-f->size];
	}
	f->size += b->size;

	// connect linked list
	free(f->data);
	free(b->data);
	f->data = tmp;
	pre_b->next = b->next;
	free(b);
}
void Cut(Node* dummy_head, int x, int idx){
    Node* prev_x = dummy_head;
    Node* list_x = dummy_head->next;
    while( --x ) list_x = list_x->next, prev_x = prev_x->next;

    int size_x1 = idx, size_x2 = list_x->size - size_x1;
    Node* list_x1 = CreateNode( size_x1 );
    Node* list_x2 = CreateNode( size_x2 );
    
    for(int i=0; i<list_x1->size; i++)
        list_x1->data[i] = list_x->data[i];
    for(int i=0; i<list_x2->size; i++)
        list_x2->data[i] = list_x->data[i + list_x1->size];
    
    prev_x->next = list_x1;
    list_x1->next = list_x2;
    list_x2->next = list_x->next;

    free(list_x->data);
    free(list_x);
}

#endif

// By Utin
```

## Reference