Reverse Linked List II
Q:
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.
A:
其实还是比较简单的,但是凭想象去交换元素的时候还是让我很烦躁,空间思维能力极差无比。。。。。。。。
没有去考虑n<m的情况,题目已经告知不用考虑这个,如果考虑的话还需要先数链表长度,当然这些问题都不重要,重要的是你需要考虑到并确认,OK
/** * 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 head; if (m > n) swap(m, n); ListNode* pre = NULL; ListNode* cur = head; ListNode* sub_head = NULL; for (int i = 1; i < m; ++i) { pre = cur; cur = cur->next; } sub_head = cur; for (int i = m; i < n; ++i) { ListNode* tmp1 = cur->next; ListNode* tmp2 = cur->next->next; cur->next->next = sub_head; cur->next = tmp2; sub_head = tmp1; } if (!pre) { head = sub_head; } else { pre->next = sub_head; } return head; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号