zoukankan      html  css  js  c++  java
  • C语言基础

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

    //定义单链表结构体
    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 
    ",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("链表销毁
    ");
    }
    

    测试打印结果

    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("源数据:
    ");
            printList(list);
    
            printf("反转后数据:
    ");
            list = reverse(list);
            printList(list);
            
            destroyList(list);
    
        }
        return 0;
    }
    

    结果:

    c-lianbiao.png

  • 相关阅读:
    Java框架之SpringMVC
    Java进阶之路
    Java入门基础教学(含配置环境变量等)
    Vue 入门学习
    WCF综合运用之:文件断点续传
    爬取集思录数据(1)--强赎表
    爬虫知识点(一)
    已知1、某股票的增减持日期,2、股票从上市至今的交易数据,求减持后(交易日)1天,5天,15天的收盘价。
    从tushare获取增减持数据
    生成文本序列
  • 原文地址:https://www.cnblogs.com/gongxiaokai/p/7123805.html
Copyright © 2011-2022 走看看