Singly Linked List in C

<!-- lang: cpp -->
#include "stdafx.h"
#include <iostream>
#include <malloc.h>

struct Node{
    int value;
    Node *next;
};

struct SLList{
    Node *head;
};

SLList* ListInit(){
    SLList *list = (SLList*)malloc(sizeof(struct SLList));
    list->head = (Node*)malloc(sizeof(struct Node));
    list->head->value = 0;
    list->head->next = (Node*)malloc(sizeof(struct Node));
    list->head->next = NULL;

    return list;
}    

Node* ListSearch(SLList *list, int value){
    Node *x = list->head;
    while(x->value != value){
        x = x->next;
    }
    if(x->value != value)
        return NULL;
    else
        return x;
}    


int ListInsert(SLList *list, int value){
    Node *x = (Node*)malloc(sizeof(struct Node));
    x->value = value;
    x->next = list->head;
    list->head = x;

    return 0;
}

int ListDel(SLList *list, int value){
    Node *temp;
    Node *x = ListSearch(list,value);
    if(x == NULL)   printf("Error: No such a Node in this list!\n");
    temp = x;
    x->next = temp->next->next;
    x->value = temp->value;

    return 0;
}

int ListShow(SLList *list){
    Node * x = list->head;
    while(x->next != NULL){
        printf(" %d ",x->value);
        x = x->next;
    }

    return 0;
}

int main(){
    SLList *list = ListInit();
    int i,j;
    for(i=1;i<=10;i++)
        ListInsert(list,i+3);

    ListShow(list);

    Node * back = ListSearch(list, 10);
    printf("\n result = %d ",back->value);


    getchar();
    return 0;
}

你可能感兴趣的:(Singly Linked List in C)