zoukankan      html  css  js  c++  java
  • 【leetcode】【92】Reverse Linked List II

    #include<iostream>
    using namespace std;
    
    struct ListNode {
    	int val;
    	ListNode *next;
    	ListNode(int x) : val(x), next(NULL) {}
    };
    
    class Solution {
    public:
    	ListNode* reverseBetween(ListNode* head, int m, int n) {
    		if (m == n)
    			return head;
    		ListNode* first = head;
    		ListNode* preFirst = head;
    		ListNode* last = head;
    		ListNode* cur = head;
    		while (--m > 0){  
    			preFirst = first;
    			first = first->next;
    		}
    		while (n-- > 0)
    			last = last->next;//调整区域是前闭后开区间
    		if (first == preFirst){ //头结点就要调整
    			cur = first->next;
    			first->next = last;
    			while (cur != last){
    				ListNode* temp = cur;
    				cur = cur->next;
    				temp->next = head;
    				head = temp;
    			}
    		}else{	//头结点不需调整
    			preFirst->next = last;
    			cur = first->next;
    			ListNode* newHead = first;
    			while (cur != last){
    				ListNode* temp = cur;
    				cur = cur->next;
    				temp->next = newHead;
    				newHead = temp;
    			}
    			first->next = preFirst->next;
    			preFirst->next = newHead;
    		}
    		return head;
    	}
    	ListNode* createList(ListNode* head){
    		int numOfNode;
    		int value;
    		cout << "please input number of listNode:";
    		cin >> numOfNode;
    		cin >> value;
    		head = new ListNode(value);
    		ListNode* cur = head;
    		for (int i = 1; i < numOfNode; ++i){
    			cin >> value;
    			ListNode* temp = new ListNode(value);
    			cur->next = temp;
    			cur = temp;
    		}
    		return head;
    	}
    	void printNode(ListNode* head){
    		ListNode* cur = head;
    		while (cur){
    			cout << cur->val << " ";
    			cur = cur->next;
    		}
    		cout << endl;
    	}
    };
    
    int main(){
    	ListNode* head = NULL;
    	Solution solution;
    	head = solution.createList(head);
    	solution.printNode(head);
    
    	head = solution.reverseBetween(head, 1, 2);
    	solution.printNode(head);
    
    	system("pause");
    	return 0;
    }

  • 相关阅读:
    hdu2138(求素数)
    hdu2104
    poj1664(放苹果)
    数塔问题给你有哪些启示?
    汉诺塔问题(1)
    算法的力量(转李开复)
    最长子序列问题之系列一
    forward和redirect的区别
    group by 和having
    java中的多态三要素是什么?
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4495555.html
Copyright © 2011-2022 走看看