38-3

设L为带头结点的单链表,编写算法实现从尾到头输出。

有两种方法

1、递归  空间复杂度O(1)

2、栈   空间复杂度O(N)

仅实现了递归算法。

#include <stdio.h>
#include <stdlib.h>

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

void TailCreate(LinkList &L)
{
    L=(LinkList)malloc(sizeof(LNode));
    L->next=NULL;
    LNode *p,*r=L;
    int x;
    scanf("%d",&x);
    while(x!=999)
    {
        p=(LNode*)malloc(sizeof(LNode));
        p->data=x;
        p->next=NULL;
        r->next=p;
        r=p;
        scanf("%d",&x);
    }
}

void ReOutput(LinkList L)
{
    if(L->next==NULL)
        return;
    L=L->next;
    ReOutput(L);
    printf("%d  ",L->data);
}

void displayList(LinkList L)
{
    LNode *p=L->next;
    while(p!=NULL)
    {
        printf("%d  ",p->data);
        p=p->next;
    }
}

int main()
{
    LinkList L;
    TailCreate(L);
    displayList(L);
    printf("\n");
    ReOutput(L);
    return 0;    
} 

 

posted on 2023-10-05 20:18  四马路弗洛伊德  阅读(17)  评论(0)    收藏  举报

导航