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* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) {
  15. SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
  16.  
  17. if (position == 0) {
  18. newNode->next = head;
  19. return newNode;
  20. }
  21.  
  22. SinglyLinkedListNode* current = head;
  23. for (int i = 0; i < position - 1 && current; i++) {
  24. current = current->next;
  25. }
  26.  
  27. if (current) {
  28. newNode->next = current->next;
  29. current->next = newNode;
  30. }
  31.  
  32. return head;
  33. }
  34.  
  35. void printList(SinglyLinkedListNode* head) {
  36. while (head) {
  37. cout << head->data << " ";
  38. head = head->next;
  39. }
  40. cout << endl;
  41. }
  42.  
  43. int main() {
  44. SinglyLinkedListNode* head = nullptr;
  45.  
  46. head = insertNodeAtPosition(head, 10, 0);
  47. head = insertNodeAtPosition(head, 20, 1);
  48. head = insertNodeAtPosition(head, 30, 2);
  49. head = insertNodeAtPosition(head, 25, 2);
  50.  
  51. printList(head);
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
10 20 25 30