遍历一次反转单链表
遍历单链表一次,反转链表。#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); }
补充:软件开发 , C++ ,