题目描述
Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes’ values. For example, Given{1,2,3,4}, reorder it to{1,4,2,3}.
class Solution {public: void reorderList(ListNode *head) { vector<int> v; ListNode *p = head; while(p!= NULL) { //把链表的元素用向量存储 v.push_back(p ->val); p = p ->next; } int i =0; int j = (int)v.size() -1; p = head; int index = 0; while(i <= j) { if(index % 2 ==0) p ->val = v[i++]; else p ->val = v[j--]; index ++; p = p ->next; } }};新闻热点
疑难解答