c实现简单链表

list.h

#ifndef LIST_H_
#define LIST_H_

struct node_t {
	int data;
	struct node_t *next;
};

struct node_list_t {
	struct node_t *head;
	int len;
};

void InitList();
int AddTailNode(struct node_t *p_sNode);
int DeleteNode(struct node_t *p_sNode);
void DumpList();
void DestroyList();

#endif

  list.cpp

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

static struct node_list_t g_sNList;

void InitList() {
    g_sNList.head = NULL;
    g_sNList.len = 0;
}

int AddTailNode(struct node_t *p_sNode) {
    struct node_t *pAddNode = (struct node_t *)malloc(sizeof(struct node_t));
    pAddNode->data = p_sNode->data;
    pAddNode->next = NULL;
    if (g_sNList.head == NULL) {
        g_sNList.head = pAddNode;
        goto END;
    }
    struct node_t *pCurNode;
    pCurNode = g_sNList.head;
    while (pCurNode->next!=NULL) {
        pCurNode = pCurNode->next;
    }
    pCurNode->next = pAddNode;
END:
    g_sNList.len++;
    return 0;
}

int DeleteNode(struct node_t *p_sNode) {
    if (g_sNList.head == NULL) {
        return -1;
    }
    struct node_t *pDelNode=NULL;
    if (g_sNList.head->data==p_sNode->data) {
        pDelNode = g_sNList.head;
        g_sNList.head = g_sNList.head->next;
        goto END;
    }
    struct node_t *pCurNode,*pPreNode;
    pPreNode = g_sNList.head;
    pCurNode = pPreNode->next;
    while (pCurNode->next!=NULL) {
        if (pCurNode->data==p_sNode->data) {
            pDelNode = pCurNode;
            pPreNode->next = pCurNode->next;
            goto END;
        }
        pPreNode = pCurNode;
        pCurNode = pCurNode->next;
    }
    if(pCurNode->data==p_sNode->data){
        pDelNode = pCurNode;
        pPreNode->next = NULL;
    }
END:
    if (pDelNode!=NULL) {
        g_sNList.len--;
        free(pDelNode);
    }
    return 0;
}

void DumpList() {

}

void DestroyList() {  

  struct node_t *pCurNode,*pDelNode;
  pCurNode = g_sNList.head;
  while (pCurNode->next != NULL) {
    pDelNode = pCurNode;
    pCurNode = pCurNode->next;
    free(pDelNode);
  }
  free(pCurNode);

}

main.cpp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"

int main() {
    int i;
    struct node_t *pCurNode=NULL;
    pCurNode = (struct node_t*)malloc(sizeof(struct node_t));

    InitList();
    for (i = 0;i < 5;i++) {
        pCurNode->data = i * 10;
        pCurNode->next = NULL;
        AddTailNode(pCurNode);
    }

    pCurNode->data = 30;
    DeleteNode(pCurNode);

    for (i = 0;i < 5;i++) {
        pCurNode->data = i * 11;
        pCurNode->next = NULL;
        AddTailNode(pCurNode);
    }

    DestroyList();

    free(pCurNode);

    printf("Over");
    getchar();
    return 0;
}

 

posted @ 2017-09-29 12:01  guanlongcun  阅读(247)  评论(0编辑  收藏  举报