逆序(算法时间复杂度为O(n))

 

#include<stdio.h>
#include<stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};

short list_Length;//全局变量list_Length记录当前表长
struct Node* head;//全局指针head, 负责指向当前链表的头结点
struct Node* rear;//全局指针rear, 负责指向当前表尾结点: 如果表为空, 那么rear指向头结点

void Create_LinkList()//创建链表, 即初始化头结点
{
    head=(struct Node*)malloc(sizeof(struct Node));
    if(head!=NULL)//结点申请成功
    {
        head->data=0;//头结点的数据域置零
        rear=head;//表尾指针暂时指向头结点
        head->next=NULL;
        list_Length=0;
    }
    else//结点申请失败
    {
        printf("头结点申请失败!\n");
    }
    return ;
}

void Node_Insert(int c)//插入新结点到链表中
{
    struct Node* p;
    p=(struct Node*)malloc(sizeof(struct Node));//申请新的Node结点
    if(p!=NULL)//结点申请成功
    {
        p->data=c;//新结点的数据由函数外传入
        p->next=NULL;
        rear->next=p;//插入结点前的表尾结点的next指针指向当前结点
        rear=p;//表尾指针指向当前新申请结点
        list_Length++;//表长+1
    }
    else
    {
        printf("结点申请失败!\n");
        return ;
    }
}

void f2()//f()函数的改进
{
    //第一步, 把数据导入数组中
    int T[list_Length];
    struct Node* p=head->next;
    int i=0;
    while(p!=NULL)
    {
        T[i]=p->data;
        p=p->next;
        i++;
    }
    //第二步, 逆序输出数组中的数据
    i=list_Length-1;
    while(i>=0)
    {
        if(i!=0)//当前输出元素不是输出序列的最后一个
            printf("%d ", T[i]);
        else//当前输出元素是输出序列的最后一个
            printf("%d\n", T[i]);
        i--;
    }
    return ;
}//时间复杂度降为O(n)

int main()
{
    int c;
    Create_LinkList();//创建头结点
    while(1)
    {
        scanf("%d", &c);
        Node_Insert(c);
        if(getchar()=='\n')
        {
            break;
        }
    }
    f2();
    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

好梦成真Kevin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值