---
# System prepended metadata

title: 12594 - Implement Linked List
tags: [NTHUOJ]

---

# 12594 - Implement Linked List
## 題解:
**Reference :** 
https://reurl.cc/pDEzAl
https://reurl.cc/Ylz2pL
## Code:
```c=1
#include "function.h"
#include <stdio.h>
#include <stdlib.h>

Node* createList(int *a, int size){
    Node *head = NULL, *cur = NULL;
    for(int i=0; i<size; i++){
        // create new new node
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = *(a + i);
        newNode->next = NULL;
        // push back
        if(head == NULL){
            head = newNode;
            cur = head;
        }
        else{
            cur->next = newNode;
            cur = cur->next;
        }
    }
    return head;
}

void push_front(Node** head, int val){
    // create new node
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = val;
    // push front
    newNode->next = *head;
    *head = newNode;
}

void deleteElementByIdx(Node** head, int idx){
    Node *cur = *head, *pre = NULL;
    while(cur != NULL && idx > 0){
        pre = cur;
        cur = cur->next;
        idx--;
    }
    if(cur == NULL)
        return;
    // pop front
    else if(cur == *head){
        *head = cur->next;
        free(cur);
        cur = NULL;
    }
    // pop
    else{
        pre->next = cur->next;
        free(cur);
        cur = NULL;
    }
}

Node* copyList(Node* head){
    if(head == NULL)
        return NULL;
    Node* cur = (Node*)malloc(sizeof(Node));
    cur->data = head->data;
    cur->next = copyList(head->next);
    return cur;
}

void SwapElementByIdx(Node** head, int idx1, int idx2){
    if(idx1 == idx2)
        return;
    // search for index1
    Node *pre_x = NULL, *cur_x = *head;
    while(cur_x != NULL && idx1 > 0){
        pre_x = cur_x;
        cur_x = cur_x->next;
        idx1--;
    }
    // search for index2
    Node *pre_y = NULL, *cur_y = *head;
    while(cur_y != NULL && idx2 > 0){
        pre_y = cur_y;
        cur_y = cur_y->next;
        idx2--;
    }
    if(cur_x == NULL || cur_y == NULL)
        return;
    // x is not head of linked list
    if(pre_x != NULL)
        pre_x->next = cur_y;
    else
        *head = cur_y;
    // y is not head of linked list
    if(pre_y != NULL)
        pre_y->next = cur_x;
    else
        *head = cur_x;
    // swap next node
    Node *temp = cur_x->next;
    cur_x->next = cur_y->next;
    cur_y->next = temp;
}
```
###### tags: `NTHUOJ`