码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_92_Reverse Linked List II

时间:2015-02-15 10:49:55      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   linked_list   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


Reverse Linked List II 

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.



//关键点有四个,1.第m-1个点,2.第m个点,3.第n个点,4.第n+1个点


//关键点有四个,1.第m-1个点,2.第m个点,3.第n个点,4.第n+1个点

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        ListNode *before, *start, *end, *after;
        before = after = start = end = NULL;        
        ListNode *ptr = head;
        for (int i = 1; i < m; i++) {
            before = ptr;
            ptr = ptr->next;            
        }
        start = end = ptr;
        for (int i = m; i <= n; i++) {
            after = ptr->next;
            ptr->next = end;
            end = ptr;
            ptr = after;            
        }
        if (before == NULL) {
            head = end;
        }
        else {
            before->next = end;
        }
        start->next = after;
        return head;
    }
};



#include<iostream>

using namespace std;

#define N 5

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        ListNode *before, *start, *end, *after;
        before = after = start = end = NULL;        
        ListNode *ptr = head;
        for (int i = 1; i < m; i++) {
            before = ptr;
            ptr = ptr->next;            
        }
        start = end = ptr;
        for (int i = m; i <= n; i++) {
            after = ptr->next;
            ptr->next = end;
            end = ptr;
            ptr = after;            
        }
        if (before == NULL) {
            head = end;
        }
        else {
            before->next = end;
        }
        start->next = after;
        return head;
    }
};


ListNode *creatlist()
{
	ListNode *head = NULL;
	ListNode *p;
	for(int i=0; i<N; i++)
	{
		int a;
		cin>>a;
		p = (ListNode*) malloc(sizeof(ListNode));
		p->val = a;
		p->next = head;
		head = p;
	}
	return head;
}

int main()
{
	ListNode *list = creatlist();
	Solution lin;
	int a ,b;
	cin>>a;
	cin>>b;
	ListNode *outlist = lin.reverseBetween ( list,a,b );
	for(int i=0; i<N; i++)
	{
		cout<<outlist->val;
		outlist = outlist->next;
	}
}





leetcode_92_Reverse Linked List II

标签:c++   leetcode   linked_list   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43833333

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!