c++经典算法 下载本文

内容发布更新时间 : 2024/6/29 13:27:10星期一 下面是文章的全部内容请认真阅读。

C++经典算法

1.链表逆序

[cpp] view plain copy

1. 2. 3. 4. 5. 6. 7. #include using namespace std;

struct node {

int value; node * next;

8. }; 9. 10. node* make_link(void); 11. node* reverse(node*); 12. void display(node *); 13. 14. int main() 15. { 16. node *head=make_link(); 17. display(head); 18. head=reverse(head); 19. display(head); 20. 21. return 0; 22. } 23. 24. node* make_link(void) 25. { 26. node *head=new node(); 27. node *cur=head; 28. for(int i=0;i<10;i++) 29. { 30. cur->value=rand(); 31. cur->next=new node(); 32. cur=cur->next; 33. } 34. 35. return head;

36. } 37.

38. node* reverse(node *head) 39. { 40. node *pre,*post,*cur; 41. if(!head && !head->next) 42. return head; 43. pre=head; 44. cur=pre->next; 45. while(cur) 46. { 47. post=cur->next; 48. cur->next=pre; 49. pre=cur; 50. cur=post; 51. } 52. head->next=NULL; 53. return pre; 54. } 55. 56. void display(node * head) 57. { 58. node * cur=head; 59. while(cur) 60. { 61. cout<value<<\; 62. cur=cur->next; 63. } 64. cout<

2.链表合并

[cpp] view plain copy

1. 2. 3. 4. 5. 6. 7. #include

using namespace std;

struct node {

int value;

8. node *next; 9. };

10. 11. node *make_list(void); 12. void display(node *); 13. void sort(node *); 14. node *merge(node *,node *); 15. 16. int main() 17. { 18. node *node1=make_list(); 19. display(node1); 20. sort(node1); 21. 22. node *node2=make_list(); 23. display(node2); 24. sort(node2); 25. 26. node *mnode=merge(node1,node2); 27. display(mnode); 28. 29. return 0; 30. } 31. 32. 33. node *make_list(void) 34. { 35. node *head=new node(); 36. node *cur=head; 37. for(int i=0;i<10;i++) 38. { 39. cur->value=rand(); 40. cur->next=new node(); 41. cur=cur->next; 42. } 43. 44. return head; 45. } 46. 47. void display(node *head) 48. { 49. node *cur=head; 50. while(cur) 51. {