Perfect solution for even reverse


#1

/**

  • Definition for singly-linked list.
  • struct ListNode {
  • int val;
    
  • ListNode *next;
    
  • ListNode(int x) : val(x), next(NULL) {}
    
  • };
    */

ListNode *reverse(ListNode *head){
ListNode *q;
q=NULL;
while(head!=NULL){
ListNode *on=head->next;
head->next=q;
q=head;
head=on;
}
return q;
}

ListNode* Solution::solve(ListNode* h){
ListNode *p, *q;
vector v;
int len=0;

p=h;
while(p!=NULL){
    if(len%2==1){
        v.push_back(p->val);
    }
    len++;
    p=p->next;
}
int idx=0;
q=reverse(h);
p=q;

if(len%2==1){
    q=q->next;
}
while(q!=NULL){
    q->val=v[idx];
    idx++;
    q=q->next->next;
}
p=reverse(p);
return p;

}