Paste Search Dynamic
Recent pastes
insertAtHead
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class node{
  5.     public:
  6.     int data;
  7.     node *next;
  8.     node(int val){
  9.         data = val;
  10.         next = null;
  11.     }
  12. };
  13. void insertAtHead(node* &head,int val){
  14.     node *n = new node(val);
  15.     if(head==null){
  16.         head = n;
  17.         return;
  18.     }
  19.     n->next = head;
  20.     head = n;
  21. }
  22. void display(node* head){
  23.     node* temp = head;
  24.     while(temp!=null){ // can also take head because it won't be modified
  25.         cout<<temp->data<<" ";
  26.         temp=temp->next;
  27.     }
  28. }
  29. node* reverse(node* &head){
  30.     node* pptr=null,*ptr=head,*nptr;
  31.     while(ptr!=null){
  32.         nptr=ptr->next;
  33.         ptr->next = pptr;
  34.         pptr = ptr;
  35.         ptr = nptr;
  36.     }
  37.     return ptr;
  38. }
  39. int main(){
  40.     node* head = null;
  41.     insertAtHead(head,5);
  42.     insertAtHead(head,10);
  43.     insertAtHead(head,15);
  44.     insertAtHead(head,20);
  45.     display(head);
  46.     cout<<"nNow reversingn";
  47.     node* newHead = reverse(head);
  48.     display(newHead);
  49.     return 0;
  50. }
  51.  
Parsed in 0.004 seconds