zoukankan      html  css  js  c++  java
  • 【leetcode】【单链表】【143】Reorder List

    #include<iostream>
    using namespace std;
    
    struct ListNode {
    	int val;
    	ListNode *next;
    	ListNode(int x) : val(x), next(NULL) {}
    };
    
    class Solution {
    public:
    	//翻转链表
    	ListNode* reverseList(ListNode* head) {
    		ListNode* cur = head;
    		ListNode* new_head = NULL;
    		while (cur){
    			ListNode* temp = cur;
    			cur = cur->next;
    			temp->next = new_head;
    			new_head = temp;
    		}
    		head = new_head;
    		return head;
    	}
    	void reorderList(ListNode* head) {
    		if (head == NULL || head->next == NULL)
    			return;
    		ListNode* slow = head;
    		ListNode* fast = head;
    		ListNode* last = head;
    		//得到list的中点
    		while (fast&&fast->next){
    			last = slow;
    			slow = slow->next;
    			fast = fast->next->next;
    		}
    		last->next = NULL;
    		last = NULL;
    		//后半段反转
    		slow=reverseList(slow);
    		fast = head;
    		ListNode* temp = NULL;
    		while (fast){
    			temp = slow;
    			slow = slow->next;
    			temp->next = fast->next;
    			fast->next = temp;
    			last = fast->next;
    			fast = fast->next->next;
    		}
    		if (slow)
    			last->next = slow;
    	}
    	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 lst;
    	head = lst.createList(head);
    	lst.printNode(head);
    
    	lst.reorderList(head);
    	lst.printNode(head);
    
    	system("pause");
    	return 0;
    }

  • 相关阅读:
    小白学开发(iOS)OC_ 使用继承来扩充类(2015-08-07)
    UI组件之TextView及其子类(三)ToggleButton和Switch
    C++智能指针--shared_ptr
    HDU 1013 Digital Roots 题解
    对touch事件传递的简单理解
    【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】
    Cocos2d-x 坐标系
    hdu1518 Square
    servlet3.0新特性
    OGNL表达式
  • 原文地址:https://www.cnblogs.com/ruan875417/p/4558300.html
Copyright © 2011-2022 走看看