Answer to Question #256099 in C for Riya

Question #256099

Write a program to traverse linked list(1-way)


1
Expert's answer
2021-10-25T03:13:11-0400
#include <stdio.h>
#include <stdlib.h>

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

void Traverse(Node *head) {
  while (head) {
    printf("%d ", head->v);
    head = head->next;
  }
}

Node* Push(Node* head, int v) {
  Node *newNode = (Node*)malloc(sizeof(Node));
  newNode->v = v;
  newNode->next = NULL;
  if (!head) {
    return newNode;
  }
  Node *n = head;
  while (n->next) {
    n = n->next;
  }
  n->next = newNode;
  return head;
}

int main()
{
  Node * head = NULL;
  for (int i = 0; i < 5; i++) head = Push(head, i + 1);
  Traverse(head);
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS