简体   繁体   中英

How to print the first node from a linked list of structs?

Below is a Minimal Reproducible Example from my code. What I am doing is that I am inserting data in a list of structs and printing them on the console.

I want to print from each link only the first element that is inserted into each list of structs.

But how is that possible when instead of data in my struct I have:

typedef struct Node 
{
    int rollnumber, src, dst;
    double gentime;
    struct Node *next;
} Node;

(rollnumber, src, dst,gentime are the information I am reading from text files, but the reading code is not nessacary, so I wrote it with testdata.)

MINIMAL REPRODUCIBLE EXAMPLE

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

#define N   10

typedef struct Node
{
  int data;
  struct Node* next;
} Node;


int push_front(Node** head, int data)
{
  Node* new_node = malloc(sizeof(Node));
  int success = new_node != NULL;

  if (success)
  {
    new_node->data = data;
    new_node->next = *head;
    *head = new_node;
  }

  return success;
}

void output(Node* head)
{
  for (Node* current = head; current != NULL; current = current->next)
  {
    printf("%d ", current->data);
  }
}

void display(Node** set, int i)
{
    output(set[i]);
    putchar('\n');
}

int main(void)
{
  int testdata = 1;
  Node* link[N] = { 0 };
  struct Node* head = NULL;

  for (int i = 0; i < N; i++) {
    push_front(&link[i], testdata++);
    push_front(&link[i], testdata++);
  }

  for (int i = 0; i < N; i++) {
    printf("link[%d]:", i);
    display(link, i);
  }
}

If I am right you want the first element of the list right??

If so than the way you are working you are pushing the new node in front of old node, so your first node is now the last in the line, so all you need to do is to iterate the list till Node* next == null, and that node will be your answer

Node *getLastInLine( Node *Head){
 Node *ptr;
 ptr = Head;
if( ptr == NULL) return NULL;
 while(ptr-> next != NULL){
  ptr = ptr->next;
 }
return ptr;
}

If you only want to print the first element of each link list, just do not loop in output :

void output(Node* head)
{
    printf("%d ", head->data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM