单链表逆序输出(递归)

将单链表逆序输出
对于单链表逆序输出不改变链表结构可以考虑使用递归实现。
递归输出的主要思路为:先输出除当前节点外的后继子链表,然后输出当前结点。假如链表为:1->2->3->4->5->6->7,那么就先输出2->3->4->5->6->7,再输出1。同理,对于链表2->3->4->5->6->7,也是先输出3->4->5->6->7,接着输出2,直到遍历到链表的最后一个结点7的时候会输出结点7,然后递归地输出6,5,4,3,2,1。
实现代码如下:

#include <bits/stdc++.h>
 
#define readup ios::sync_with_stdio(0)

using namespace std;

typedef struct LNode
{
    
    
    int data;
    struct LNode *next;
}LNode,*LinkList;

void ReversePrint(LinkList firstNode)
{
    
    
    if(firstNode==NULL)return;

    ReversePrint(firstNode->next);
    cout<<firstNode->data<<' ';
}

int main()
{
    
    
    int n;
    cin>>n;
    LinkList head=(LinkList)malloc(sizeof(LNode));
    head->next=NULL;
    LinkList tmp=NULL;
    LinkList cur=head;
    for(int i=1;i<=n;i++)
    {
    
    
        tmp=(LinkList)malloc(sizeof(LNode));
        cin>>tmp->data;
        tmp->next=NULL;
        cur->next=tmp;
        cur=tmp;
    }
    //cout<<"顺序输出:";
    for(cur=head->next;cur;cur=cur->next)
        cout<<cur->data<<' ';
    cout<<endl;
    //cout<<"逆序输出:";
    ReversePrint(head->next);
    for(cur=head->next;cur;)
    {
    
    
        tmp=cur;
        cur=cur->next;
        free(tmp);
    }
    return 0;
}

算法性能:只需要都链表进行一次遍历,因此时间复杂度为O(n)。

猜你喜欢

转载自blog.csdn.net/Stephen_Curry___/article/details/126772503