Advertisement
Guest User

Untitled

a guest
Jun 24th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node{
  6. int data;
  7. Node* next;
  8. };
  9.  
  10. Node* head;
  11.  
  12. void print();
  13. void insert(int x, int pos);
  14. void deleteNode(int pos);
  15. void insertAtEnd(int x);
  16. void reversePrint();
  17. void recPrint(Node* temp);
  18. void recReversePrint(Node* temp);
  19.  
  20. int main(){
  21. head = NULL;
  22.  
  23. insert(2,1); //2
  24. insert(3,2); //2 3
  25. insert(6,1); //6 2 3
  26. insert(0,2); //6 0 2 3
  27. insertAtEnd(7); // 6 0 2 3 7
  28. insertAtEnd(9); // 6 0 2 3 7 9
  29. insert(5,2); //6 5 0 2 3 7 9
  30. recPrint(head);
  31. recReversePrint(head);
  32. return 0;
  33. }
  34.  
  35. void insert(int x, int pos){
  36. Node* temp = head;
  37. Node* n = new Node();
  38. n->data = x;
  39. if(pos == 1){
  40. n->next = head;
  41. head = n;
  42. return;
  43. }
  44.  
  45. for(int i =1;i<=pos-2;i++){
  46. temp=temp->next;
  47. }
  48.  
  49. n->next = temp->next;
  50. temp->next = n;
  51.  
  52. }
  53.  
  54. void print(){
  55. Node* temp = head;
  56.  
  57. while(temp!=NULL){
  58. cout << temp->data << " " ;
  59. temp = temp->next;
  60. }
  61. cout<<endl;
  62. }
  63.  
  64.  
  65. void insertAtEnd(int x){
  66. Node* temp = new Node();
  67. temp->data = x;
  68. temp->next = NULL;
  69.  
  70. Node* ptr = head;
  71. while(ptr->next!=NULL){
  72. ptr = ptr->next;
  73. }
  74. ptr->next = temp;
  75. }
  76.  
  77.  
  78. void recPrint(Node* temp){
  79.  
  80. if(temp == NULL) {
  81. cout<<endl;
  82. return;
  83. }
  84. cout << temp->data << " ";
  85. recPrint(temp->next);
  86.  
  87. }
  88. void recReversePrint(Node* temp){
  89.  
  90. if(temp == NULL) {
  91. cout<<endl;
  92. return;
  93. }
  94.  
  95. recReversePrint(temp->next);
  96. cout << temp->data << " ";
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement