赞
踩
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
接下来,用伪代码演示一下
- ListNode* pre指向1,也就是反转区间的前一位。
- ListNode* cur指向2,反转区间首位。
- ListNode* temp=cur->next,指向3。
-
- 先让3指向2,我们让temp->next=cur,
- 再让2指向4,cur->next=temp->next;
- 可是这里的temp.next,被修改了,所以这两句顺序要颠倒一下。
-
- 先让2指向4,cur->next=temp->next;
- 再让3指向2,temp->next=cur;
- 然后1指向3,pre->next=temp
目前: 1->3->2->4->5
pre指向1,cur指向2,temp指向3
现在目标是让4掉到3前面,让temp指向4
- 先让4指向3:temp->next=pre.next;
- 再让2指向5:cur->next=temp->next;
- 同样,temp->next发生了改变,颠倒一下语句顺序
- 先让2指向5:cur->next=temp->next;
- 再让4指向3:temp->next=pre.next;
- 再让1指向4:pre->next=temp;
完整代码:
- #include<iostream>
- #include<string>
- using namespace std;
- typedef struct ListNode {
- int val;
- struct ListNode* next;
- }ListNode, * List;
- void createList(List L,int n) {
- ListNode* r = L;
- for (int i = 0; i < n; i++) {
- ListNode* p = new ListNode;
- cin >> p->val;
- p->next = NULL;
- r->next = p;
- r = r->next;
- }
- }
- ListNode* reverseBetween(ListNode* head, int m, int n) {
- //加个表头
- ListNode* r = new ListNode;
- r->next = head;
- //前序节点
- ListNode* pre = r;
- //当前节点
- ListNode* cur = head;
- //找到m
- for (int i = 1; i < m; i++) {
- pre = cur;
- cur = cur->next;
- }
- //从m反转到n
- for (int i = m; i < n; i++) {
- ListNode* temp = cur->next;
- cur->next = temp->next;
- temp->next = pre->next;
- pre->next = temp;
- }
- //返回去掉表头
- return r->next;
- }
- void printList(List L) {
- ListNode* p = L;
- while (p) {
- cout << p->val << " ";
- p = p->next;
- }
- }
- int main() {
- List L = new ListNode;
- L->next = NULL;
- int x;
- cout << "请输入链表长度:";
- cin >> x;
- createList(L, x);
- cout << "请输入反转区间:";
- int m, n;
- cin >> m >> n;
- printList(reverseBetween(L->next, m, n));
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。