单链表的逆序

单链表的逆序有以下几种方法:
第一种方法:堆栈法,将原链表元素依序push如堆栈中,然后再pop入新链表中,时空复杂度依然过大,但是这种方法时空复杂度较高;
第二种方法:运用数组。即先遍历单链表取出元素顺序放到数组中,然后从数组中逆序取出元素,再次遍历单链表时放入。这种方法也需要额外建立数组,而且需要遍历两次。
第三种方法:直接逆序。 仅遍历一遍
第四种方法:递归。
下面是代码

#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
//include<stack.h>
struct node
{
    int n;
    struct node *next;
};

struct node *creatnode(int n)//创建链表
{
    struct node *head=(struct node*)malloc(sizeof(struct node));
    struct node *p=NULL;
    struct node *q=NULL;

    head->n=1;
    head->next=NULL;
    p=head;

    for(int i=1;i<n;i++)
    {
        q=(struct node*)malloc(sizeof(struct node));
        q->n=i+1;
        q->next=NULL;

        p->next=q;
        p=q;
    }
    if(n<1)
    {
        free(head);
        return NULL;
    }
    else
        return head;
}

void prin(struct node* head)//打印链表
{
    struct node* p=head;
    if(p->next==NULL)
        cout<<"这是一个空链表"<<endl;
    while(p!=NULL)
    {
        cout<<p->n<<" ";
        p=p->next;
    }
    cout<<endl;
}
struct node* reverse(struct node* head)//直接逆序
{
    struct node *p=head;
    struct node *q=p->next;
    head->next=NULL;
    if(q==NULL)
        return q;
    while(q)
    {
        p=q;
        q=q->next;
        p->next=head;
        head=p;
    }
    return head;
}
struct node* direverse(struct node* head)//递归实现链表逆序
{
    if(!head || !head->next )   
            return head;
    struct node* newhead = direverse(head->next);
    head->next->next = head;
    head->next = NULL;

    return newhead;
}
struct node *arrar_reverse(struct node* head)//使用数组实现链表逆序
{
    struct node *p=head;
    int a[10],i=0;
    while(p)
    {
        a =p->n;
        i++;
        p=p->next;
    }
    p=head;
    while(p)
    {
        p->n=a[i-1];
        --i;
        p=p->next;
    }
    return head;
}
/*struct node *push_reverse(struct node* head)//使用栈实现链表逆序//没写完,待完善
{
    struct node *p=head;
    int i=0;
    while(p)
    {
        push(p->n);
        p=p->next;
    }
    p=head;
    while(p)
    {
        i=pop();
        p->n=i;
        p=p->next;
    }
    return head;
}*/
void main()
{
    struct node *head;
    head=creatnode(8);
    prin(head);
    head=reverse(head);
    prin(head);
    head=direverse(head);
    prin(head);
    head=arrar_reverse(head);
    prin(head);
}
结果为:

1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
Press any key to continue
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值