如何获得与示例相同的输出?

问题描述 投票:0回答:1
#include <stdio.h>
#include<stdlib.h>
#include<assert.h>
#include <stdbool.h>

typedef struct node { 
  int data; 
  struct node *next; 
} NodeT;


NodeT *makeNode(int v);
NodeT *joinLL(NodeT *head, int v);
void showLL(NodeT *head);
void freeLL(NodeT *head);
int a;

int main(void){
   
   NodeT *head= NULL;
   bool bo=true;
   while (bo){
      printf("Enter an integer:");
      if (scanf("%d", &a)){
          head=joinLL(head, a);
     }
       else{
          printf("Done");
          break;
        }
    
   }
    
    showLL(head);
    freeLL(head);
    return 0;
    
}


//creat a new node
NodeT *makeNode(int v) { 
  NodeT *new = malloc(sizeof(NodeT)); 
  assert(new != NULL); 
  new->data = v; // initialise data
  new->next = NULL; // initialise link to next node
  return new; // return pointer to new node
}


//append a new element with data v at the end of list.
NodeT *joinLL(NodeT *head, int v) {
    NodeT *insert = makeNode(v);

    if (head==NULL){
        return insert;
    }

    NodeT *temp = head;

    while (temp->next != NULL){
        temp = temp->next;
    }

    temp->next = insert;

    return head;
}


    

void showLL(NodeT *head) {

    //iterate the entire linked list and print the data
   NodeT *p;
   printf("List is ");
   for (p = head; p!= NULL; p = p->next) {
        int elements= p->data;
        printf("%d-->",elements);
   }
}


void freeLL(NodeT *head) {
   NodeT *p, *temp;

   p = head;
   while (p != NULL) {
      temp = p->next;
      free(p);
      p = temp;
   }
}

我想让输出是:

enter an integer: a number1

enter an integer : a number2

enter an integer : a number3

enter an integer : a non-numeric character

Done. List is  number1-->number2-->number3.

if I enter an integer: a non-numeric character

print: Done.

我认为代码会有一点变化,但不知道如何使用示例获得相同的输出。

c printf
1个回答
0
投票

试试这个

void showLL(NodeT* head) {

    //iterate the entire linked list and print the data
    NodeT* p;
    printf("List is ");
    for (p = head; p != NULL; p = p->next) {
        int elements = p->data;
        printf("%d", elements);
        //print an arrow only if there's a next node
        if (p->next) printf("--->");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.