Singly Linked List With Header

From Ta Wiki
Jump to navigation Jump to search

Linked List แบบทางเดียว แบบมี header ด้วย (Header node คือ node ที่ไม่เก็บค่าจริงๆ เป็นตัวเริ่มต้นแค่นั้น)

#include<stdio.h>
typedef int DType;
typedef struct node{
    DType data;
    struct node *next;
}node;

node* createList(){
    node *header = (node*)malloc(sizeof(node));
    header -> next = NULL;
}

void insert(node *pos, DType val){ // INSERT AFTER pos
    node *temp = (node*)malloc(sizeof(node));
    temp->data = val;
    temp->next = pos->next;
    pos->next = temp;
}

void erase(node *header, DType val){ // ERASE val THAT IS IN linked lists
    node *temp = header;
    while(temp->next != NULL){
        if(temp->next->data == val){
            node *del = temp->next;
            temp->next = temp->next->next;
            free(del);
            break;
        }
    }
}

int main(){
    node *header = createList();
    insert(header,15);
    printf("%d\n",header->next->data);
    erase(header,15);
    
    if(header->next == NULL) printf("NULL\n");
    else printf("NOT NULL\n");
    
    scanf(" ");
    return 0;
}