Answer to Question #256109 in C for Jahnvi

Question #256109

Write a program to insert an element in stack(Push operation only).


1
Expert's answer
2021-10-25T03:13:08-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;
  }
}

// insert an element in stack(Push operation only).
Node* Push(Node* head, int v) {
  Node *newNode = (Node*)malloc(sizeof(Node));
  newNode->v = v;
  newNode->next = head;
  return newNode;
}

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