前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C语言基础 - 实现单向链表

C语言基础 - 实现单向链表

作者头像
gwk_iOS
发布2018-08-23 11:03:04
1.4K0
发布2018-08-23 11:03:04
举报
文章被收录于专栏:coding...coding...

写在前面 弄了下个人站...防止内容再次被锁定...所有东西都在这里面 welcome~ 个人博客

回归C基础 实现一个单向链表,并有逆序功能 (大学数据结构经常是这么入门的)

代码语言:javascript
复制
//定义单链表结构体
typedef struct Node{
    int value;
    struct Node *next;
}Node;

//创建链表
Node* createNode(int value,Node *next){
    Node *node = malloc(sizeof(Node));
    node->value = value;
    node->next = next;
    return node;
}

//打印链表
void printList(Node *list){
    for (Node *node = list; node != NULL; node = node->next) {
        printf("current node value %d \n",node->value);
    }
    
}

//反转链表
Node* reverse(Node *listNode){
    Node *reList = NULL;
    Node *tmp;
    while (listNode != NULL) {
        tmp = malloc(sizeof(Node));
        //逆转之后,原链表的头结点就是新链表的尾结点
        //如果不是第一个结点,则本次产生的新结点是上次结点的前一个
        if (reList == NULL) {
            tmp->next = NULL;
        }else{
            tmp->next = reList;
        }
        tmp->value = listNode->value;
        reList = tmp;
        listNode = listNode->next;
    }
    //原链表的最后一个结点是新链表的头结点
    return reList;
}

//销毁
void destroyList(Node *list){
    Node *tmp;

    while (list != NULL) {
        tmp = list;
        list = list->next;
        free(tmp);
    }
    printf("链表销毁\n");
}

测试打印结果

代码语言:javascript
复制
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Node *first = createNode(0, NULL);
        Node *list = first;
        
        first->next = createNode(2, NULL);
        first = first->next;
        
        first->next = createNode(3, NULL);
        first = first->next;
        
        first->next = createNode(4, NULL);
        first = first->next;
        
        first->next = createNode(7, NULL);
        first = first->next;
        
        printf("源数据:\n");
        printList(list);

        printf("反转后数据:\n");
        list = reverse(list);
        printList(list);
        
        destroyList(list);

    }
    return 0;
}

结果:

c-lianbiao.png

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.12.15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档