LeetCode | Reverse Linked List II
2016-07-31 16:48
309 查看
这道链表反转题也是搞的我焦头烂额,好久没有写链表了,注意记忆这些
Reverse Linked List II QuestionEditorial Solution My Submissions Total Accepted: 78774 Total Submissions: 274380 Difficulty: Medium
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 Linked List II QuestionEditorial Solution My Submissions Total Accepted: 78774 Total Submissions: 274380 Difficulty: Medium
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.
直接贴代码吧
//看到这样的题目需要分析一下具体有哪些种类,而不是盲目地将其分类 class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { //分为m=1或者n=linklist.size()-1或者二者都是或者二者都不是 ///(ㄒoㄒ)/~~4种情况 // ListNode* temp=head,a,b,apre,bpre; // int count=0; // while(temp!=NULL){ // count++; // if(count==m) a=temp; // else if(count==n) b=temp; // } // // temp=head; // while(temp!=NULL){ // //找到了a之前的节点 // if(temp->next==a) { // apre=temp; // } // } // 上面这种放弃 //由于leetcode上链表都是从第一项开始的 //所以必须得手动添加一个链表头 ListNode root(-1); root.next=head; ListNode* pre=&root; //注意链表也可以通过for循环来实现遍历 //不要觉得只有while(temp->next!=NULL)这种 for(int i=1;i<m;i++) pre=pre->next; //开启第二链表头,从这里引出链表到目的节点 //cur表示当前指针 ListNode* head2=pre; //注意我们要以何种方式进行遍历 //从第m个数开始需要被交换[3,5] //这里pre=pre->next之后,pre->val=3,pre->next->val=5; //再通过下面的交换就可以替换3和5的位置 pre=pre->next; ListNode* cur=pre->next; //对之后的进行遍历 for(int i=m;i<n;i++){ pre->next=cur->next; //头部插入数据 //如果没有那一步pre=pre->next;那么这里cur->next=head2->next即(pre->next),就会落到5上,这样head2->next就没有被交换 cur->next=head2->next; head2->next=cur; cur=pre->next; } return root.next; } };
相关文章推荐
- LeetCode92 Reverse Linked List II
- [LeetCode] Reverse Linked List II
- LeetCode Reverse Linked List II
- 【leetcode】【单链表】【92】Reverse Linked List II
- [Leetcode 73] 92 Reverse Linked List II
- Reverse Linked List II [LeetCode]
- leetcode 76: Reverse Linked List II
- leetcode:Reverse Linked List II
- LeetCode(92) Reverse Linked List II
- [leetcode] Reverse Linked List II
- LeetCode Reverse Linked List II
- LeetCode Reverse Linked List I, II详解
- LeetCode Reverse Linked List II
- LeetCode 92. Reverse Linked List II
- Leetcode: Reverse Linked List II
- leetcode: Reverse Linked List II
- LeetCode - M - Reverse Linked List II
- LeetCode[Linked List]: Reverse Linked List II
- LeetCode 92. Reverse Linked List II
- Leetcode Reverse Linked List II