您的位置:首页 > 其它

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.

这道题很简单,但是需要细心。

对于链表等问题都需要细心。

代码如下:

/*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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: