C examples for Data Structure:Linked List
Create Circular Linked List
#include <stdio.h> #include <stdlib.h> typedef struct node { int num;// ww w . java2 s. c o m struct node *next; } Node, *NodePtr; NodePtr linkCircular(int); NodePtr removeLastChild(NodePtr, int, int); int main() { NodePtr curr; int n, m; do { printf("Enter number of children and length of count-out: "); scanf("%d %d", &n, &m); } while (n < 1 || m < 1); curr = linkCircular(n); //link children in a circular list curr = removeLastChild(curr, n-1, m); printf("The winning child: %d\n", curr -> num); } NodePtr makeNode(int n) { NodePtr np = (NodePtr) malloc(sizeof (Node)); np -> num = n; np -> next = NULL; return np; } NodePtr linkCircular(int n) { NodePtr first, np, makeNode(int); first = np = makeNode(1); //first child for (int h = 2; h <= n; h++) { //link the others np -> next = makeNode(h); np = np -> next; } np -> next = first; //set last child to point to first return first; } NodePtr removeLastChild(NodePtr first, int x, int m) { NodePtr prev, curr = first; for (int h = 1; h <= x; h++) { for (int c = 1; c < m; c++) { prev = curr; curr = curr -> next; } prev -> next = curr -> next; free(curr); curr = prev -> next; //set curr to the child after the one eliminated } return curr; }