链表倒置

前端之家收集整理的这篇文章主要介绍了链表倒置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #include"iostream"
  2. using namespace std;
  3.  
  4.  
  5. struct node
  6. {
  7. int data;
  8. struct node *next;
  9. };
  10. typedef struct node Node;
  11. node * reverse( node * head)
  12. {
  13. node * p,*q;
  14. p=head->next;
  15. head->next = NULL;
  16. while(p!=NULL)
  17. {
  18. q=p;
  19. p=p->next; //修改q会修改p所指的值,所以必须先对p进行保护
  20. q->next = head->next;
  21. head->next=q;
  22. }
  23. return head;
  24. }
  25.  
  26. int main()
  27. {
  28. node head,*p,*q;
  29. int i;
  30. head.next=NULL;
  31. for(i=0;i<10;i++)
  32. {
  33. p = new node;
  34. p->next=NULL;
  35. p->data=i;
  36. if(head.next==NULL)
  37. head.next=p;
  38. else
  39. q->next=p;
  40. q=p;
  41.  
  42. }
  43. p=head.next;
  44. while(p!=NULL)
  45. {
  46. cout<<p->data<<" ";
  47. p=p->next;
  48. }
  49. cout<<endl;
  50.  
  51. p= reverse(&head);
  52. p=p->next;
  53. while(p!=NULL)
  54. {
  55. cout<<p->data<<" ";
  56. p=p->next;
  57. }
  58. cout<<endl;
  59. return 0;
  60. }

注意指针在使用前必须初始化

猜你在找的设计模式相关文章