Reverse Linked List II
2013-09-29 11:42
239 查看
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if (m>n) return NULL; if (m==n) return head; ListNode *res=new ListNode(0); res->next=head; ListNode *cur=head, *pre=res, *start=NULL; int i; for (int i=1; i<=n; i++) { if (i==m) { start=pre; } if (i>m && i<=n) { pre->next=cur->next; cur->next=start->next; start->next=cur; cur=pre; } pre=cur; cur=cur->next; } return res->next; } };
reference: http://leetcode.com/2010/04/reversing-linked-list-iteratively-and.html
The second time
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (!head) return NULL; if (m==n) return head; int len=1; ListNode *pre=new ListNode(0); pre->next=head; ListNode *res = pre; while (len<m) { pre=pre->next; len++; if (!pre) { return res->next; } } ListNode *cur=pre->next; ListNode *nex=cur->next; while (nex) { cur->next=nex->next; nex->next=pre->next; pre->next=nex; nex=cur->next; len++; if (len==n) { break; } } return res->next; } };
相关文章推荐
- Reverse Linked List II
- Reverse Linked List II -- leetcode
- Reverse Linked List II 局部翻转链表@LeetCode
- LeetCode 60 Reverse Linked List II
- leetcode - Reverse Linked List II
- Reverse Linked List II
- Leetcode 92. Reverse Linked List II
- [LeetCode] Reverse Linked List II
- Leetcode:Reverse Linked List II 单链表区间范围内逆置
- 【leetcode】【92】Reverse Linked List II
- [LeetCode] Reverse Linked List II @ Python [提供自创的示意图 Figure illustration]
- 【LeetCode】Reverse Linked List II
- LeetCode: Reverse Linked List II [092]
- LeetCode - M - Reverse Linked List II
- reverse linked list II
- Reverse Linked List II && Add Binary
- LeetCode 92. Reverse Linked List II
- Reverse Linked List II
- 92. Reverse Linked List II
- leetcode Reverse Linked List II