首页 > 其他 > 详细

c 链表

时间:2020-03-08 13:14:02      阅读:63      评论:0      收藏:0      [点我收藏+]

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;
}

  

c 链表

原文:https://www.cnblogs.com/luckygxf/p/12441592.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!