当前位置:   article > 正文

C++链表内指定区间反转_c++怎么反转区间

c++怎么反转区间

1->2->3->4->5反转区间是[2,4],结果即1->4->3->2->5。

步骤1:把3掉到2前面:1->3->2->4->5

步骤2:把4掉到3前面:1->4->3->2->5

接下来,用伪代码演示一下

  1. ListNode* pre指向1,也就是反转区间的前一位。
  2. ListNode* cur指向2,反转区间首位。
  3. ListNode* temp=cur->next,指向3
  4. 先让3指向2,我们让temp->next=cur,
  5. 再让2指向4,cur->next=temp->next;
  6. 可是这里的temp.next,被修改了,所以这两句顺序要颠倒一下。
  7. 先让2指向4,cur->next=temp->next
  8. 再让3指向2,temp->next=cur;
  9. 然后1指向3,pre->next=temp

目前: 1->3->2->4->5

pre指向1,cur指向2,temp指向3

现在目标是让4掉到3前面,让temp指向4

  1. 先让4指向3:temp->next=pre.next;
  2. 再让2指向5:cur->next=temp->next;
  3. 同样,temp->next发生了改变,颠倒一下语句顺序
  4. 先让2指向5:cur->next=temp->next;
  5. 再让4指向3:temp->next=pre.next;
  6. 再让1指向4:pre->next=temp;

完整代码:

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. typedef struct ListNode {
  5. int val;
  6. struct ListNode* next;
  7. }ListNode, * List;
  8. void createList(List L,int n) {
  9. ListNode* r = L;
  10. for (int i = 0; i < n; i++) {
  11. ListNode* p = new ListNode;
  12. cin >> p->val;
  13. p->next = NULL;
  14. r->next = p;
  15. r = r->next;
  16. }
  17. }
  18. ListNode* reverseBetween(ListNode* head, int m, int n) {
  19. //加个表头
  20. ListNode* r = new ListNode;
  21. r->next = head;
  22. //前序节点
  23. ListNode* pre = r;
  24. //当前节点
  25. ListNode* cur = head;
  26. //找到m
  27. for (int i = 1; i < m; i++) {
  28. pre = cur;
  29. cur = cur->next;
  30. }
  31. //从m反转到n
  32. for (int i = m; i < n; i++) {
  33. ListNode* temp = cur->next;
  34. cur->next = temp->next;
  35. temp->next = pre->next;
  36. pre->next = temp;
  37. }
  38. //返回去掉表头
  39. return r->next;
  40. }
  41. void printList(List L) {
  42. ListNode* p = L;
  43. while (p) {
  44. cout << p->val << " ";
  45. p = p->next;
  46. }
  47. }
  48. int main() {
  49. List L = new ListNode;
  50. L->next = NULL;
  51. int x;
  52. cout << "请输入链表长度:";
  53. cin >> x;
  54. createList(L, x);
  55. cout << "请输入反转区间:";
  56. int m, n;
  57. cin >> m >> n;
  58. printList(reverseBetween(L->next, m, n));
  59. return 0;
  60. }

 

 

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