#include<iostream>
#include<vector>
using namespace std;
//Definition for singly-linked list.
/*Given a singly linked list L : L 0→L 1→…→L n - 1→L n,
reorder it to : L 0→L n →L 1→L n - 1→L 2→L n - 2→…*/
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}
};//class Solution { //没有考虑将最后一个结点删除,并把第二个结点的指针域置为空
//public: //思路错误
// void reorderList(ListNode *head) {
// if (head == NULL || head->next==NULL)
// return;
// ListNode *pEnd = head->next;
// while (pEnd) {
// pEnd = pEnd->next;
// }
// pEnd->next = head->next;
// head->next = pEnd;
// }
//};
class Solution {
public:void reorderList(ListNode *head) {ListNode* p = head; //保留头结点ListNode *rear = head; while(p!=NULL && p->next!=NULL){ while (rear->next->next!=NULL) { //找到倒数第二个结点rear = rear->next;}ListNode *temp = rear->next; //保留最后一个结点rear->next = NULL; //将倒数第二个结点的指针域置为空//插入temp(最后一个结点)将temp插入到p(头结点)和p->next之间temp->next = p->next;p->next = temp; //将结点插入rear = temp->next; //保留结点为插入结点的后一个结点p = temp->next; //将头结点保留为插入结点的后一个结点}}
};//大神思路
class Solution {
public:void reorderList(ListNode *head) {if (!head) return;vector<int> V;ListNode* ptr = head;/*for(; ptr!=NULL; ptr=ptr->next){V.push_back(ptr->val);}*/while (ptr != NULL) {V.push_back(ptr->val);ptr = ptr->next;}int i = 0;int j = V.size() - 1;int flag = 0;ptr = head;while (i <= j) {if ((flag % 2) == 0) {ptr->val = V[i]; i += 1;}else {ptr->val = V[j]; j -= 1;}++flag;ptr = ptr->next;}}
};