fork download
  1. //
  2. // main.cpp
  3. // Delete from Linked List
  4. //
  5. // Created by Himanshu on 15/09/21.
  6. //
  7.  
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. struct node {
  12. int info = 0;
  13. struct node *next;
  14. };
  15. typedef struct node Node;
  16.  
  17. node* newNode(int data)
  18. {
  19. node* Node = new node();
  20. Node->info = data;
  21. Node->next = NULL;
  22.  
  23. return(Node);
  24. }
  25.  
  26. void printLinkedList (Node* head) {
  27. Node *x = head;
  28.  
  29. while (x != NULL) {
  30. cout<<(x->info)<<" ";
  31. x = x->next;
  32. }
  33. cout<<endl;
  34. }
  35.  
  36. Node* insertNode (Node *head, Node* x) {
  37. x->next = head;
  38. head = x;
  39. return head;
  40. }
  41.  
  42. void deleteNode (Node* x) {
  43. if (x == NULL) {
  44. return;
  45. } else if (x->next == NULL) {
  46. cout<<"Last node can't be deleted without head pointer"<<endl;
  47. return;
  48. }
  49. Node* temp = x->next;
  50. x->info = temp->info;
  51. x->next = temp->next;
  52. delete (temp);
  53. }
  54.  
  55.  
  56. int main(int argc, const char * argv[]) {
  57. Node *head = newNode(7);
  58. head = insertNode (head, newNode(6));
  59. head = insertNode (head, newNode(5));
  60. head = insertNode (head, newNode(4));
  61. head = insertNode (head, newNode(3));
  62. head = insertNode (head, newNode(2));
  63. head = insertNode (head, newNode(1));
  64.  
  65. cout<<"Linked List:"<<endl;
  66. printLinkedList(head);
  67.  
  68. cout<<"Deleting Node 1"<<endl;
  69. deleteNode(head);
  70.  
  71. cout<<"Linked List:"<<endl;
  72. printLinkedList(head);
  73.  
  74. cout<<"Deleting Node 4"<<endl;
  75. deleteNode(head->next->next);
  76.  
  77. cout<<"Linked List:"<<endl;
  78. printLinkedList(head);
  79.  
  80. cout<<"Deleting Node 7"<<endl;
  81. deleteNode(head->next->next->next->next);
  82.  
  83. cout<<"Linked List:"<<endl;
  84. printLinkedList(head);
  85.  
  86. return 0;
  87. }
  88.  
Success #stdin #stdout 0s 5396KB
stdin
Standard input is empty
stdout
Linked List:
1 2 3 4 5 6 7 
Deleting Node 1
Linked List:
2 3 4 5 6 7 
Deleting Node 4
Linked List:
2 3 5 6 7 
Deleting Node 7
Last node can't be deleted without head pointer
Linked List:
2 3 5 6 7