当前位置:   article > 正文

链表反转C++_链表转置c++

链表转置c++

给定一个有序链表进行反转

  1. #include <iostream>
  2. using namespace std;
  3. #include <vector>
  4. struct ListNode
  5. {
  6. int value;
  7. ListNode* next;
  8. ListNode(int x):value(x),next(NULL) {}
  9. };
  10. ListNode* reverseList(ListNode* head)
  11. {
  12. ListNode* temp;
  13. ListNode* pre = NULL;
  14. ListNode* cur = head;
  15. while (cur)
  16. {
  17. temp = cur->next;
  18. cur->next = pre;
  19. pre = cur;
  20. cur = temp;
  21. }
  22. return pre;
  23. }
  24. void printList(ListNode* head)
  25. {
  26. while (head)
  27. {
  28. cout << head->value;
  29. head = head->next;
  30. if (head)
  31. cout << "->";
  32. }
  33. cout << endl;
  34. }
  35. int main()
  36. {
  37. //创建链表
  38. ListNode* head = new ListNode(1);
  39. ListNode* n1 = new ListNode(2);
  40. ListNode* n2 = new ListNode(3);
  41. ListNode* n3 = new ListNode(4);
  42. ListNode* n4 = new ListNode(5);
  43. ListNode* n5 = new ListNode(6);
  44. head->next = n1;
  45. n1->next = n2;
  46. n2->next = n3;
  47. n3->next = n4;
  48. n4->next = n5;
  49. n5->next = NULL;
  50. cout << "反转前:" << endl;
  51. printList(head);
  52. ListNode* node=reverseList(head);
  53. cout << "反转后:" << endl;
  54. printList(node);
  55. system("pause");
  56. return 0;
  57. }

输出结果

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/lpred/article/detail/62863
推荐阅读
相关标签
  

闽ICP备14008679号