fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <stack>
  4. #include <queue>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. struct node {
  10. int data;
  11. node* link;
  12. };
  13.  
  14. node* head = NULL;
  15.  
  16. void clear();
  17. bool isEmpty();
  18. void insertFront(int value);
  19. void insertLast(int value);
  20. void display();
  21. int sumlink();
  22. int nodeCount();
  23. void delFront();
  24. void delLast();
  25.  
  26. int main()
  27. {
  28. insertFront(10);
  29. insertFront(20);
  30. insertFront(30);
  31. display();
  32. delLast();
  33. display();
  34. cout << "sum = " << sumlink() << endl;
  35. delFront();
  36. display();
  37. }
  38.  
  39. void clear() {
  40. head = NULL;
  41. }
  42.  
  43. bool isEmpty() {
  44. if (head == NULL)
  45. return true;
  46. else
  47. return false;
  48. }
  49.  
  50. void insertFront(int value) {
  51. node* N = new node;
  52. N->data = value;
  53. N->link = NULL;
  54. if (head == NULL)
  55. head = N;
  56. else {
  57. N->link = head;
  58. head = N;
  59. }
  60. }
  61.  
  62. void insertLast(int value) {
  63. node* newnode = new node;
  64. newnode->data = value;
  65. newnode->link = NULL;
  66. node* temp = head;
  67. while (temp->link != NULL) {
  68. temp = temp->link;
  69. }
  70. temp->link = newnode;
  71. }
  72.  
  73. void display() {
  74. cout << "The data is : \n";
  75. if (head == NULL)
  76. cout << "Linked LIst is Empty\n";
  77. else {
  78. node* temp = head;
  79. while (temp != NULL) {
  80. cout << temp->data << endl;
  81. temp = temp->link;
  82. }
  83. }
  84. }
  85.  
  86. int sumlink() {
  87. int sum = 0;
  88. node* temp = head;
  89. while (temp != NULL) {
  90. sum += temp->data;
  91. temp = temp->link;
  92. }
  93. return sum;
  94. }
  95.  
  96. int nodeCount() {
  97. int cnt = 0;
  98. node* temp = head;
  99. while (temp != NULL) {
  100. cnt++;
  101. temp = temp->link;
  102. }
  103. return cnt;
  104. }
  105.  
  106. void delFront() {
  107. if (head == NULL)
  108. cout << "The list is underflow\n";
  109. else {
  110. node* temp = head;
  111. cout << "The deleted item is :" << head->data << endl;
  112. head = head->link;
  113. delete temp;
  114. }
  115. }
  116.  
  117. void delLast() {
  118. if (head == NULL)
  119. cout << "The list is underflow\n";
  120. else if (head->link == NULL) {
  121. delete (head);
  122. head = NULL;
  123. }
  124. else {
  125. node* kk = head;
  126. while (kk->link->link != NULL) {
  127. kk = kk->link;
  128. }
  129. delete(kk->link);
  130. kk->link = NULL;
  131. }
  132.  
  133. }
Success #stdin #stdout 0.01s 5332KB
stdin
Standard input is empty
stdout
The data is : 
30
20
10
The data is : 
30
20
sum = 50
The deleted item is :30
The data is : 
20