leetcode 92. Reverse Linked List II 反转链表 + 头插入反转链表(或者使用栈)
2017-09-12 12:41
441 查看
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.
这道题很简单,但是需要细心。
对于链表等问题都需要细心。
代码如下:
下面是C++的做法,就是一个简单的链表反转问题,可以直接使用头部插入法反转,或者使用栈来完成反转
代码如下:
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 ListNode { int val; ListNode next; ListNode(int x) { val = x; } } */ /* * 链表反序问题,这个很简单,但是需要很细心 * */ public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head==null || head.next==null) return head; ListNode newHead=new ListNode(0); newHead.next=head; ListNode pre=newHead,start=null,then=null; for(int i=0;i<m-1;i++) pre=pre.next; start=pre.next; then=start.next; for(int i=0;i<n-m;i++) { start.next=then.next; then.next=pre.next; pre.next=then; then=start.next; } return newHead.next; } }
下面是C++的做法,就是一个简单的链表反转问题,可以直接使用头部插入法反转,或者使用栈来完成反转
代码如下:
#include <iostream> #include <algorithm> #include <vector> #include <stack> using namespace std; /* struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; */ class Solution { public: ListNode* reverseBetween(ListNode* h, int m, int n) { if (h == NULL || h->next == NULL || m==n) return h; stack<ListNode*> sk; int count = 0; ListNode* head = new ListNode(-1); head->next = h; ListNode* pre = head; for (int i = 0; i < m - 1; i++) pre = pre->next; ListNode* start = pre->next; ListNode* then = start->next; for (int i = 0; i < n - m; i++) { start->next = then->next; then->next = pre->next; pre->next = then; then = start->next; } return head->next; } };
相关文章推荐
- (Leetcode)92. Reverse Linked List II ——反转单链表
- leetCode 92.Reverse Linked List II (反转链表II) 解题思路和方法
- LeetCode-92-Reverse Linked List II 链表反转 各种边界条件
- LeetCode2.2.2 @ Reverse Linked List II 反转链表II D3F2
- leetcode解题之206 # Reverse Linked List Java版 (使用头插法反转链表)
- LeetCode 92. Reverse Linked List II(翻转链表)
- Leetcode Reverse Linked List II 反转部分单向链表
- leetcode之92. Reverse Linked List II(C++读错题版本,交换一个链表中指定的两个位置上的元素)
- [leetcode] 【链表】92. Reverse Linked List II
- [leetcode]Reverse Linked List II (反转链表值 C语言实现)
- [Leetcode] Reverse linked list ii 反转链表
- [leetcode] Reverse Linked List II 链表反转
- leetcode:Reverse Linked List II (反转链表中的一部分)【面试算法题】
- [LeetCode-92] Reverse Linked List II(反转指定区间链表)
- Leetcode 92. Reverse Linked List II 翻转链表2 解题报告
- Leetcode Reverse Linked List II 反转特定区间的链表
- 92. Reverse Linked List II【遍历一遍就反转链表】
- 【LeetCode-面试算法经典-Java实现】【092-Reverse Linked List II(反转单链表II)】
- leetcode206/92---Reverse Linked List I/II(反转链表)
- LeetCode-Reverse Linked List II(反转链表)