Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct _node{
- int data;
- struct _node *next;
- };
- typedef struct _node node;
- void inputNode(node*, int);
- void printNode(node*, int);
- node* reverseNodes(node*);
- int main(){
- node *head, *ptr;
- head = new node;
- // initialize data value
- int n;
- cout << "how many struct do you need: "; cin >> n;
- inputNode(head,n);
- printNode(head,n);
- // reverse it
- head = reverseNodes(head);
- printNode(head,n);
- // free memory
- delete head;
- }
- void inputNode(node* ptr, int n){
- int value;
- for (int i = 0; i < n; i++){
- if (i == 0){
- cout << "Please input the value for " << i+1 << " struct: " ;
- cin >> value;
- ptr->data = value;
- continue;
- }
- ptr->next = new node;
- ptr = ptr->next;
- cout << "Please input the value for " << i+1 << " struct: " ;
- cin >> value;
- ptr->data = value;
- }
- }
- void printNode(node* ptr, int n){
- for (int i = 0; i < n; i++){
- cout << "the value for " << i+1 << " struct: " << ptr->data << endl;
- ptr = ptr->next;
- }
- }
- node* reverseNodes(node *headToReverse){
- node* ptr = headToReverse;
- node *left, *right = NULL;
- while( ptr != NULL){
- left = right; // for the first one, it's NULL
- right = ptr; // point to the current place
- ptr = ptr->next; // point to the next place // this must precede the next command
- right->next = left; // reverse the direction one by one
- }
- return right; // the new start is now the memory location of right;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement