#include <iostream> #include <fstream> using namespace std; struct LinkNode { int data; LinkNode* next; }; LinkNode* createLink(LinkNode* head) { ifstream fin; fin.open("list.txt"); if(!fin){ cout << "open file failed......" << endl; return head; } LinkNode* tail = NULL; int data; while(fin>>data){ LinkNode* node = new LinkNode(); node->data = data; node->next = NULL; //cout << data << endl; if(head==NULL){ head=node; tail=node; } else{ tail->next = node; tail = node; } } return head; } LinkNode* reverseLink(LinkNode* head) { LinkNode* node = head; LinkNode* reverseHead = NULL; LinkNode* pre = NULL; LinkNode* next = NULL; while(node!=NULL){ next = node->next; if(next == NULL){ reverseHead = node; } node->next = pre; pre = node; node = next; } return reverseHead; } void print(LinkNode* head) { if(head == NULL){ cout << "linknode is null" <<endl; return; } LinkNode* node = head; while(node!=NULL){ cout << node->data <<endl; node = node->next; } } int main() { LinkNode* head = NULL; head = createLink(head); print(head); head = reverseLink(head); print(head); return 0; }
时间: 2024-10-18 20:27:27