Advertisement
uopspop

Untitled

May 3rd, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct _node{
  5.     int data;
  6.     struct _node *next;
  7. };
  8. typedef struct _node node;
  9.  
  10. void inputNode(node*, int);
  11. void printNode(node*, int);
  12. node* reverseNodes(node*);
  13.  
  14. int main(){
  15.     node *head, *ptr;
  16.     head = new node;   
  17. // initialize data value
  18.     int n;
  19.     cout << "how many struct do you need: "; cin >> n;
  20.     inputNode(head,n);
  21.     printNode(head,n);
  22.  
  23. // reverse it
  24.     head = reverseNodes(head);
  25.     printNode(head,n);
  26.  
  27. // free memory
  28.     delete head;
  29. }
  30.  
  31.  
  32.  
  33.  
  34. void inputNode(node* ptr, int n){
  35.     int value;
  36.     for (int i = 0; i < n; i++){
  37.         if (i == 0){
  38.             cout << "Please input the value for " << i+1 << " struct: " ;
  39.             cin >> value;
  40.             ptr->data = value;
  41.             continue;          
  42.         }
  43.        
  44.         ptr->next = new node;
  45.         ptr = ptr->next;
  46.  
  47.         cout << "Please input the value for " << i+1 << " struct: " ;
  48.         cin >> value;
  49.         ptr->data = value;
  50.     }
  51. }
  52.  
  53. void printNode(node* ptr, int n){
  54.     for (int i = 0; i < n; i++){
  55.         cout << "the value for " << i+1 << " struct: " << ptr->data << endl;
  56.         ptr = ptr->next;
  57.     }
  58. }
  59.  
  60. node* reverseNodes(node *headToReverse){
  61.     node* ptr = headToReverse;
  62.     node *left, *right = NULL;
  63.     while( ptr != NULL){
  64.         left = right; // for the first one, it's NULL
  65.         right = ptr; // point to the current place
  66.         ptr = ptr->next;  // point to the next place // this must precede the next command
  67.         right->next = left; // reverse the direction one by one
  68.     }
  69.     return right; // the new start is now the memory location of right;
  70. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement