C-language concatenation list reverses output order

Asked 2 years ago, Updated 2 years ago, 38 views

Prerequisite
There are some problems with the list structure of the c language that just don't work.

What do you want to do
There are no errors in the program itself, but the output is displayed in reverse order, and it seems to be inserted in reverse order of the order in which you want to insert.Please point out the parts that should be corrected so that the output is correct.

Affected Source Code

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

US>structure node {
    care element;
    structure node*next;
};

structure node*initlist(){
  structure node*n;
  n = (struct node*) malloc (size of (struct node);
  n - > next = NULL;
  return n;
}

void insert(struct node*p, charx){
  structure node*n;
  n=(struct node*)malloc(sizeof(struct node)));
  n->element=x;
  n->next=p->next;
  p->next=n;
}
void printlist(struct node*p){
    if(p->next==NULL){
        putchar('\n');
    } else {
        p=p->next;
        putchar(p->element);
        printlist(p);
        putchar(p->element);
    }
}

int main(intargc, char*argv[]){
    structure node*list, *head;
    char*p;
    if(argc<2)
        exit(-1);

    list = initlist();
    p = argv[1];
    for (;*p;p++)
        insert(list,*p);

    printlist(list);
    printf("\n");
    for(;list;){
        head=list;
        list = list->next;
        free(head);
    }
    return 0;
}

Correct Output

 [ ]$ gcc-Wall-std = c99-o q5-1 q5-1.c
[ ] $./q5-1abcde
abcde
edcba

My output

 [ ]$ gcc-Wall-std = c99-o q5-1 q5-1.c
[ ] $./q5-1abcde
edcba
abcde

c

2022-09-30 19:44

1 Answers

I learned from another question site and changed the insert function as follows, and the output was successful.

 void insert (struct node*p, char x) {
  structure node*n;
  n=(struct node*)malloc(sizeof(struct node)));
  n->element=x;
  n - > next = NULL;
  while(p->next!=NULL)
    p=p->next;
  p->next=n;
}


2022-09-30 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.