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 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;
}
};