C examples for Data Structure:Linked List
Create a linked list in reversed order, add new numbers at the head of the list
#include <stdio.h> #include <stdlib.h> typedef struct node { int num;// w w w.ja va 2 s . co m struct node *next; } Node, *NodePtr; void printList(NodePtr); NodePtr makeNode(int); int main() { int n = 1; NodePtr top = NULL, np; printf("type a number, 0 to stop:\n"); while (n != 0) { np = makeNode(n); //create a new node containing n np -> next = top; //set link of new node to first node top = np; //set top to point to new node printf("type a number, 0 to stop:\n"); if (scanf("%d", &n) != 1) n = 0; } printList(top); } NodePtr makeNode(int n) { NodePtr np = (NodePtr) malloc(sizeof (Node)); np -> num = n; np -> next = NULL; return np; } void printList(NodePtr np) { while (np != NULL) { // as long as there's a node printf("%d\n", np -> num); np = np -> next; // go on to the next node } }