#include #include // Structure that represents a singly-linked-list of integers struct LinkedListItem { int data; struct LinkedListItem *next; }; // Takes a list tail and adds the given item to it, returning the new item added struct LinkedListItem *add(struct LinkedListItem *tail, int item) { struct LinkedListItem *newItem; newItem = (struct LinkedListItem *) malloc(sizeof(struct LinkedListItem)); if (newItem == NULL) { printf("Memory allocation error\n"); exit(0); } newItem->data = item; newItem->next = NULL; if (tail != NULL) tail->next = newItem; return newItem; } // Add all elements from items to the given Singly-Linked List and // set the list to point to the head of the resulting list void addAll(struct LinkedListItem **initTail, int items[], int size) { struct LinkedListItem *newItem; struct LinkedListItem *tail = *initTail; for (int i=0; idata = items[i]; newItem->next = NULL; if (tail != NULL) tail->next = newItem; else *initTail = newItem; // newItem becomes the head of the list tail = newItem; } } // Print the contents of a Singly-Linked List void printList(struct LinkedListItem *listItem) { while(listItem != NULL) { printf("%d", listItem->data); if (listItem->next != NULL) printf(" ---> "); else printf("\n"); listItem = listItem->next; } } // Free all items in a Singly-Linked List void freeList(struct LinkedListItem *listItem) { struct LinkedListItem *nextItem; while(listItem != NULL) { nextItem = listItem->next; free(listItem); listItem = nextItem; } } int main() { struct LinkedListItem *myList = NULL, *yourList = NULL; add(add(add(add(add(add(add(myList = add(NULL, 23),65),87),45),56),34),95),71); int initData[] = {23, 65, 87, 45, 56, 34, 95, 71}; addAll(&yourList, initData, sizeof(initData)/sizeof(int)); printList(myList); printf("\n"); printList(yourList); freeList(myList); freeList(yourList); }