Write a program to traverse linked list(1-way)
#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;
}
Comments
Leave a comment