fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct SinglyLinkedListNode {
  5. int data;
  6. SinglyLinkedListNode* next;
  7.  
  8. SinglyLinkedListNode(int val) {
  9. data = val;
  10. next = nullptr;
  11. }
  12. };
  13.  
  14. SinglyLinkedListNode* deleteNode(SinglyLinkedListNode* head, int position) {
  15. if (!head) return nullptr;
  16.  
  17. if (position == 0) {
  18. SinglyLinkedListNode* temp = head;
  19. head = head->next;
  20. delete temp;
  21. return head;
  22. }
  23.  
  24.  
  25. SinglyLinkedListNode* current = head;
  26. for (int i = 0; i < position - 1 && current->next; i++) {
  27. current = current->next;
  28. }
  29.  
  30. if (current->next) {
  31. SinglyLinkedListNode* temp = current->next;
  32. current->next = temp->next;
  33. delete temp;
  34. }
  35.  
  36. return head;
  37. }
  38.  
  39.  
  40. void printList(SinglyLinkedListNode* head) {
  41. while (head) {
  42. cout << head->data << " ";
  43. head = head->next;
  44. }
  45. cout << endl;
  46. }
  47.  
  48. int main() {
  49.  
  50. SinglyLinkedListNode* head = new SinglyLinkedListNode(10);
  51. head->next = new SinglyLinkedListNode(20);
  52. head->next->next = new SinglyLinkedListNode(30);
  53. head->next->next->next = new SinglyLinkedListNode(40);
  54.  
  55. int position = 2;
  56. head = deleteNode(head, position);
  57.  
  58. printList(head);
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
10 20 40