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

  • 相关阅读:
    数据库表分区
    将对象序列化成XML字符串
    [邀月博客] SQL Server 2008中SQL增强之二:Top新用途
    多线程:子线程执行过程中调用主线程
    Jquery版文字闪烁
    金马自定义对联
    清除数据
    QQ、微信、QQ浏览器UserAgent
    jump.html域名跳转javascript版
    注册页面位置调整
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4495555.html
Copyright © 2020-2023  润新知