fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct SinglyLinkedListNode {
  5. int data;
  6. SinglyLinkedListNode* next;
  7.  
  8. SinglyLinkedListNode(int node_data) {
  9. data = node_data;
  10. next = nullptr;
  11. }
  12. };
  13.  
  14. SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
  15. SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
  16.  
  17. if (!head) {
  18. return newNode;
  19. }
  20.  
  21. SinglyLinkedListNode* temp = head;
  22. while (temp->next) {
  23. temp = temp->next;
  24. }
  25. temp->next = newNode;
  26.  
  27. return head;
  28. }
  29.  
  30.  
  31. void printList(SinglyLinkedListNode* head) {
  32. while (head) {
  33. cout << head->data << " ";
  34. head = head->next;
  35. }
  36. cout << endl;
  37. }
  38.  
  39. int main() {
  40. SinglyLinkedListNode* head = nullptr;
  41.  
  42.  
  43. head = insertNodeAtTail(head, 10);
  44. head = insertNodeAtTail(head, 20);
  45. head = insertNodeAtTail(head, 30);
  46.  
  47. printList(head);
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
10 20 30