遍歷單鏈表一次,反轉鏈表。
#include<iostream> using namespace std; typedef struct NODE { NODE(int v) { value=v; next=NULL; } int value; NODE* next; }Node; void printList(NODE* head) { cout<<head->value<<" "; if(head->next) printList(head->next); return; } NODE* reverseList(NODE* head) { NODE* currentNode=head; NODE* lastNode=NULL; NODE* nextNode=currentNode->next; while(nextNode) { currentNode->next=lastNode; lastNode=currentNode; currentNode=nextNode; nextNode=nextNode->next; } currentNode->next=lastNode; return currentNode; } bool test(NODE* first,NODE* second) { return first==second; } void main() { NODE node1(1); NODE node2(2); node1.next=&node2; NODE node3(3); node2.next=&node3; NODE node4(4); node3.next=&node4; NODE node5(5); node4.next=&node5; NODE* inithead=&node1; printList(inithead); cout<<"開始反轉:"<<endl; NODE* head=reverseList(inithead); if(test(&node4,head->next)) cout<<"反轉測試測功"<<endl; printList(head); }