首页 > 学院 > 开发设计 > 正文

leetcode之reorder-list

2019-11-06 07:38:19
字体:
来源:转载
供稿:网友

题目描述

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; } }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表