开发者

C: Printing linked list backwards

开发者 https://www.devze.com 2023-03-30 00:30 出处:网络
Trying to print this list backwards 开发者_Python百科user inputs 10 characters, program prints out 10 characters in original order then in reverse order.

Trying to print this list backwards

开发者_Python百科user inputs 10 characters, program prints out 10 characters in original order then in reverse order.

Thanks to you guys I figured out the problem why it wouldn't print in regular order, now I'm having some trouble getting it to print in reverse order..

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

#define strsize 30

typedef struct member
{
    int number;
    char fname[strsize];
    struct member *next;
} RECORD;

RECORD* insert (RECORD *it);
RECORD* print(RECORD *it, int j);

int main (void)
{
    int i;
    double result;
    RECORD *head, *p;
    head=NULL;
    result=10;

    for (i=1; i<=result; i++)
        head=insert (head);  
    print (head, result);

    return 0;

}

RECORD* insert (RECORD *it)
{

    RECORD *cur, *q; 
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%s", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));

    strcpy(cur->fname, first);
    cur->next=NULL; 

    if (it==NULL)
        it=cur;
    else
    {
        q=it;
        while (q->next!=NULL)
            q=q->next;
        q->next=cur;
    }

    return (it);
}

RECORD* print(RECORD *it, int j)
{
    RECORD *cur;
    cur=it;
    int i;
    for(i=1;i<=j;i++)
    {
        printf("%s \n", cur->fname);
        cur=cur->next;

        //my solution for printing it backwards..

        void print(node *it)
        {
            if(it!=NULL)
            {
                print(it->next);
                printf("%s-->",it->number);
            }
        }

        return;
    }
}


You have several "things" going by the name print

  • a prototype: RECORD* print(RECORD *it, int j);
  • a call, inside main: print (head, result);
  • a function definition: RECORD* print(RECORD *it, int j) {
  • a nested function definition: void print(node *it) {

The first three are coherent, but the last one is just plain wrong.

Also
Standard C does not allow nested functions.
The type node is not defined.
You still need to work on your indentation :)

0

精彩评论

暂无评论...
验证码 换一张
取 消