c 链表

list.h

//
// Created by gxf on 2020/3/8.
//

#ifndef UNTITLED_LINKLIST_H
#define UNTITLED_LINKLIST_H

typedef struct ListNodeS {
    int data;
    struct ListNodeS *next;
} ListNode;

ListNode* initList();
void addList(ListNode *head, int data);
void printAllNode(ListNode *head);
ListNode* createNode(int data);
void travelList(ListNode *head);
ListNode* createList(int *array, int size);

#endif //UNTITLED_LINKLIST_H

 list.c

//
// Created by gxf on 2020/3/8.
//
#include "linklist.h"
#include <stdlib.h>
#include <stdio.h>

ListNode *initList() {
    ListNode *head = malloc(sizeof(ListNode));
    head->data = 0;
    head->next = NULL;
    return head;
}

ListNode* createNode(int data) {
    ListNode *node = malloc(sizeof(ListNode));
    node->data = data;
    node->next = NULL;
    return node;
}

void addList(ListNode *head, int data) {
    ListNode *tmp = createNode(data);
    while (head->next) {
        head = head->next;
    }
    head->next = tmp;
}

void travelList(ListNode *head) {
    ListNode *curPoint = head->next;
    while (curPoint) {
        printf("%d ", curPoint->data);
        curPoint = curPoint->next;
    }
    printf("\n");
}

ListNode *createList(int *dataArray, int size) {
    ListNode *head = createNode(0);
    ListNode *tmpHead = head;
    for (int i = 0; i < size; i++) {
        ListNode *tmpNode = createNode(dataArray[i]);
        tmpHead->next = tmpNode;
        tmpHead = tmpHead->next;
    }
    return head;
}

  main.c

//
// Created by gxf on 2020/3/8.
//
#include "linklist.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void printHello();

int main() {
    int array[5] = {1, 2, 3, 4, 5};
    ListNode *head = createList(array, sizeof(array) / sizeof(int));
    travelList(head);

    ListNode *head1 = initList();
    addList(head1, 1);
    addList(head1, 2);
    addList(head1, 3);

    travelList(head1);

    return 0;
}

  

posted on 2020-03-08 11:48  luckygxf  阅读(124)  评论(0编辑  收藏  举报

导航