fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class List{
  5. private:
  6. typedef struct Node{
  7. int data;
  8. struct Node* next;
  9. }* node;
  10.  
  11. node head;
  12. int listLength;
  13.  
  14. public:
  15. List();
  16. List(int data, node nextLink);
  17. void printList();
  18. void push(int data);
  19. void Delete(int d);
  20. int listSize(void);
  21. };
  22.  
  23. List::List(){
  24. head = NULL;
  25. listLength=0;
  26. }
  27.  
  28. List::List(int data, node nextLink){
  29. head = new Node;
  30. head->data = data;
  31. head->next = nextLink;
  32. listLength = 1;
  33. }
  34.  
  35. void List::push(int data){
  36. if(head==NULL){
  37. head = new Node; // added this line
  38. head->data=data;
  39. head->next= NULL;
  40. }else{
  41. node cursor = head;
  42. while(cursor->next != NULL)
  43. cursor = cursor -> next;
  44.  
  45. node newNode= new Node;
  46. newNode->data=data;
  47. newNode->next=NULL;
  48. cursor->next= newNode;
  49. }
  50. listLength++;
  51. }
  52.  
  53. void List::printList(){
  54. node cursor=head;
  55. while(cursor!=NULL){
  56. //if(cursor->data==0){cursor=cursor->next;}
  57. if(cursor->next==NULL){
  58. cout<<cursor->data<<endl;
  59. return;
  60. }
  61. else{
  62. cout<<cursor->data<<" -> ";
  63. cursor=cursor->next;
  64. }
  65.  
  66. }
  67. cout<<endl;
  68. }
  69. int main(){
  70. List li;
  71. li.push(2);
  72. li.push(3);
  73. li.push(0);
  74. li.push(4);
  75. li.printList();
  76. return 0;
  77. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
2 -> 3 -> 0 -> 4