fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. // Structure definitions
  6. // Node in doubly-linked list
  7.  
  8. typedef struct DLN {
  9. struct DLN *prev; // Pointer to previous list element
  10. struct DLN *next; // Pointer to next list element
  11. char *word;
  12. } DLNode;
  13.  
  14. // Actual doubly-linked list
  15. typedef struct {
  16. DLNode *firstNode; // Pointer to first node in list
  17. DLNode *lastNode; // Pointer to last node in list
  18. } DLList;
  19.  
  20. // Function prototypes
  21.  
  22. void addNode(DLList *list, const char *str) {
  23. DLNode *newNode = (DLNode*)malloc(sizeof(DLNode));
  24.  
  25. if (newNode == NULL) {
  26. fprintf(stderr, "Error:Could not allocate new node\n");
  27. exit(0);
  28. }
  29.  
  30. //list is empty, add one node
  31. if ((list->firstNode == NULL) && (list->lastNode == NULL)) {
  32. list->firstNode = newNode;
  33. list->lastNode = newNode;
  34. newNode->next=NULL;
  35. newNode->prev=NULL;
  36.  
  37. newNode->word = (char*)malloc(strlen(str) + 1);
  38.  
  39. if (newNode->word == NULL) {
  40. fprintf(stderr, "Error:Could not allocate new string for node\n");
  41. exit(0);
  42. }
  43.  
  44. strcpy(newNode->word, str); // newNode->word is large enough, so this is safe.
  45. }
  46. }
  47.  
  48. int main(void) {
  49. DLList list = { NULL, NULL };
  50. addNode(&list, "Worddhfkjsdfhaskjlfhadskjfl");
  51. puts(list.firstNode->word);
  52. }
  53.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Worddhfkjsdfhaskjlfhadskjfl