92. Reverse Linked List II
来源:互联网 发布:国际阿里云注册 编辑:程序博客网 时间:2024/06/07 14:26
问题描述
Reverse a linked list from position m to n. Do it in-place and in one-pass.For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.解决思路
首先找到需要reverse的区间段,然后依次将前面的插入到后面即可。需要主要的是,这里可以在head前面弄多一个节点,可以巧妙处理m=1的情况。代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (m == n) return head; ListNode *pre = new ListNode(0); pre->next = head; ListNode *front_cur, *front_pre, *back_cur,*back_pre,*tmp,*cur = head,*begin = pre; int count = 0; while(cur != NULL) { ++count; if (count == m) { front_cur = cur; front_pre = pre; } if (count == n) { back_cur = cur; back_pre = pre; break; } pre = cur; cur = cur->next; } count = 0; while(count++ < n-m) { front_pre->next = front_cur->next; front_cur->next = back_cur->next; back_cur->next = front_cur; front_cur = front_pre->next; } return begin->next; }};
0 0
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 92. Reverse Linked List II
- 使用阿里的maven仓库
- 算法的时间复杂度
- Android存储
- Falcon(一)——数据集管理和数据处理平台
- codeforces 777C Alyona and Spreadsheet(预处理+思维)
- 92. Reverse Linked List II
- 为什么Java中1000==1000为false而100==100为true?
- IE\firfox\chrome的差异和兼容问题
- 像VS一样简单的打包“控制台”程序
- could not resolve host: github.com 问题解决办法
- springmvc入门
- 每天一题LeetCode[第十五天]
- Command python setup.py egg_info failed with error code 1
- C#编程使用Managed Wifi API连接wifi整理(一)