zoukankan      html  css  js  c++  java
  • 链表反转

    /***
    reverse.c
    ***/
    #include<stdio.h>
    #include<stdlib.h>
    
    struct list
    {
        int data;
        struct list *next;
    };
    
    struct list *create_list()
    {
        return calloc(sizeof(struct list),1);
    }
    
    struct list *insert_list(struct list *ls,int n,int data)
    {
        struct list *p = ls;
        while(p && n--)
        {
            p = p->next;
        }
        if(NULL == p)
        {
            return NULL;
        }
        struct list *node = create_list();
        node->data = data;
        node->next = p->next;
        p->next = node;
        return node;
    }
    
    void traverse(struct list *ls)
    {
        struct list *p = ls;
        while(p)
        {
            printf("%d
    ",p->data);
            p = p->next;
        }
    }
    
    void reverse(struct list *ls)
    {
        if(ls->next == NULL)
        {
            return;
        }
    
        if(ls->next->next == NULL)
        {
            return;
        }
    
        struct list *last = ls->next;
    
        struct list *pre = ls;
        struct list *cur = ls;
        struct list *next = NULL;
    
        while(cur)
        {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        
        ls->next = pre;
        last->next = NULL;
    
    }
    
    int main()
    {
        struct list *first = create_list();
        int i;
        for(i = 0; i < 10; i++)
        {
            insert_list(first,0,i);
        }
        traverse(first);
        reverse(first);
        printf("reverse
    ");
        traverse(first);
        return 0;    
    }

    运行结果:

    ubuntu1604@ubuntu:~/wangqinghe/C/20190730$ gcc reverse.c -o reverse

    ubuntu1604@ubuntu:~/wangqinghe/C/20190730$ ./reverse

    0

    9

    8

    7

    6

    5

    4

    3

    2

    1

    0

    reverse

    0

    0

    1

    2

    3

    4

    5

    6

    7

    8

    9

    问题:创建链表时多了一个0,存疑

  • 相关阅读:
    Editplus中添加System.out.println()快捷键
    API使用
    项目有两个红点
    no console to display at this time
    startup.bat闪退问题
    filter的dispatcher节点
    【DP专题】——洛谷P2467地精部落
    输入年月日,计算这是该年中第几天
    输出N以内的完整数
    python中关于EOF的tips
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11271489.html
Copyright © 2011-2022 走看看