面試題-單鏈表的逆序
阿新 • • 發佈:2019-02-07
#include <stdlib.h> #include <stdio.h> #include <iostream> #include <time.h> #define _random(x) (random()%x) using namespace std; struct LinkNode { int data; LinkNode* next; }; LinkNode* ReverseLink(LinkNode* head) { LinkNode *prev=NULL, *next=NULL; while(head) { next = head->next; head->next = prev; prev = head; head = next; } return prev; } int main() { LinkNode* first = NULL; LinkNode* cur = NULL; srandom((int)time(0)); for(int i=0; i<10; ++i) { LinkNode* pa = new LinkNode; pa->data = _random(100); if(cur) { cur->next = pa; } else { first = pa; } cur = pa; } cur->next = NULL; cur = first; while(cur) { cout<<cur->data<<" "; cur = cur->next; } cout<<endl; LinkNode* header = ReverseLink(first); while(header) { cout<<header->data<<" "; header = header->next; } cout<<endl; return 0; }
輸出結果:
這裡沒有采用遞迴的寫法,感覺遞迴的寫法, 不太好理解, 且實戰性稍差.
簡單的流程介紹:
分析的很透徹.