• 单链表实例+反转


    单链表的定义:

    struct node
    {
    int num;
    struct node *p;
    } ;

    在链表节点的定义中,除一个整型的成员外,成员p是指向与节点类型完全相同的指针。

    在链表节点的数据结构中,非常特殊的一点就是结构体内的指针域的数据类型使用了未定义成功的数据类型。这是在C中唯一规定可以先使用后定义的数据结构。

    一个例子:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct node {
        int num;
        struct node *next;
    };
    
    struct node *init_head()
    {
        struct node *new = (struct node *)malloc(sizeof(struct node));
    
        new->num = 0;
        new->next = NULL;
    
        return new;
    }
    
    struct node * add_node(struct node *head, int num)
    {
        struct node *new = (struct node *)malloc(sizeof(struct node));
    
        new->num = num;
        new->next = head->next; 
        head->next = new;
    
        return head;
    }
    
    struct node *reverse_list(struct node *head)
    {
        struct node *p1, *p2, *p3;
    
        if (head == NULL)
        {
            return NULL;
        }
    
        p1 = head;
        p2 = head->next;
    
        while(p2)
        {
            p3 = p2->next;
            p2->next = p1;
            p1=p2;
            p2=p3;
        }
    
        head->next = NULL;
        head = p1;
    
        return head;
    }
    
    struct node *print_list(struct node *head)
    {
        struct node *tmp;
        
        tmp = head;
    
        while(head != NULL)
        {
            printf("%d, ", head->num);
            head = head->next;
        }
    
        return tmp;
    }
    
    void release_list(struct node *head)
    {
        struct node *tmp = NULL;
        
        while(head != NULL)
        {
            tmp = head;
            head = head->next;
            free(tmp);
        }
    
        return;
    }
    
    int main()
    {
        struct node *head = NULL;
        int i;
    
        head = init_head();
        
        for (i=1; i< 10; i++)
        {
            add_node(head, i);
        }
    
        printf("old list:");
        print_list(head->next);
        printf("
    ");
    
    
        head->next = reverse_list(head->next);
    
        printf("new list:");
        head = print_list(head->next);
        printf("
    ");
    
        release_list(head);
    
        return 0;
    }

    输出为

    old list:9, 8, 7, 6, 5, 4, 3, 2, 1, 
    new list:1, 2, 3, 4, 5, 6, 7, 8, 9,
  • 相关阅读:
    Winform中用了皮肤控件之后,报错:容量超出了最大容量 参数名:capacity
    C# 生成二维码
    T-sql语句修改数据库逻辑名、数据库名、物理名
    ASP.NET MVC中使用jQuery时的浏览器缓存问题
    关于asp.net页面缓存
    关于VS 工具箱灰色,不可用的解决方案
    Android
    如何让一个DIV水平,垂直方向都居中于浏览器?
    cookie.setPath()的用法
    CSS选择器
  • 原文地址:https://www.cnblogs.com/maxpak/p/5570365.html
Copyright © 2020-2023  润新知