[问题表述]
单链表逆置的算法,不管是递归还是非递归的情况下,其实策略有多种,此处只列出其中一种
[问题解答]
/* * main.cpp * * Created on: 2009-6-24 * Author: NeeSky */ #include <iostream> using namespace std; /** *Single Link List and Its Node’s definition */ typedef struct TNode { int k; TNode *next; } Node , *SingleLink; /*** *Create Single Link List, and the min Content integer is StartContent * @param len: Link’s Node number * @param startContent: len+startContent-1 –> … –> startContent * @param end: the last node’s next pointer */ SingleLink CreateSingleLink(const int len, int startContent, Node *end ) { Node *pNode = NULL; Node *postNode = end; for (int i = 0; i < len; ++i) { pNode = new Node; pNode->k = i + startContent; pNode->next = postNode; postNode = pNode; } return pNode; } /*** * Reverse The SingleLink * @return the Head Pointer */ SingleLink ReverseSingleLinkWhile(SingleLink sLink ) { Node *head = sLink; Node *p1 = head; Node *p2 = head; while (p2->next != NULL) //Assigned the value { head = p2->next;p2->next = head->next;head->next = p1; p1 = head; } return head; } /*** * Reverse the SingLink with Recusrse method * @param sLink * @param p * @return Head of Singlink */ SingleLink ReverseSingleLinkRecurse(SingleLink sLink, Node * p = 0) { if(p==0)p=sLink->next; if (p != NULL) { Node *head = p; if (p->next != NULL) { swap(p->k, p->next->k);head = p->next;p->next = head->next;head->next = sLink; sLink = head; return ReverseSingleLinkRecurse(sLink, p); //Recurse Method } else { Node *tour=sLink; while(tour->next!=p)tour=tour->next; tour->next=NULL;p->next=sLink; sLink=p; return sLink; //the exit of Recurse } } return sLink; //the exit of Recurse } /*** * Show the SingleLinkList * @param sLink */ void ShowSingleLinkList(SingleLink sLink ) { Node *p = sLink; cout << “SingleLink(“<<sLink<<“) “; for (; p != NULL; p = p->next) { cout << “->(“<<p<<“)” << p->k; } cout << endl; return; } /*** * The Main Programming * @return */ int main() { SingleLink sLink = CreateSingleLink(10, 1, NULL ); ShowSingleLinkList(sLink); sLink = ReverseSingleLinkWhile(sLink); ShowSingleLinkList(sLink); sLink=ReverseSingleLinkRecurse(sLink); ShowSingleLinkList(sLink); return 0; }
[程序的输出]:
SingleLink(0x3d2578) ->(0x3d2578 )10->(0x3d2568)9->(0x3d2558)8->(0x3d2548)7->(0x3d2538)6->(0x3d2528)5->(0x3d2518)4->(0x3d2508)3->(0x3d24f8)2->(0x3d2490)1
SingleLink(0x3d2490) ->(0x3d2490)1->(0x3d24f8)2->(0x3d2508)3->(0x3d2518)4->(0x3d2528)5->(0x3d2538)6->(0x3d2548)7->(0x3d2558)8->(0x3d2568)9->(0x3d2578)10
SingleLink(0x3d24f8) ->(0x3d24f8 )10->(0x3d2578 )9->(0x3d2568)8->(0x3d2558)7->(0x3d2548)6->(0x3d2538)5->(0x3d2528)4->(0x3d2518)3->(0x3d2508)2->(0x3d2490)1
注意红色的部分“地址”不同是 由于采取的策略方式的原因。