class Solution {
public:
/**
* 按照左右半区的方式重新组合单链表
* 输入:一个单链表的头节点head
* 将链表调整成题目要求的样子
*
* 后台的单链表节点类如下:
*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
void relocateList(struct ListNode* head) {
ListNode* p = head;
vector<int> vec;
while (p != NULL) {
vec.push_back(p->val);
p = p->next;
}
p = head;
int index = 0;
int left_index = 0;
int right_index = vec.size() / 2;
while (index<vec.size()-1 && p != NULL) {
if (index % 2 == 0) {
p->val = vec[left_index++];
p = p->next;
}
else if (index % 2 != 0) {
p->val = vec[right_index++];
p = p->next;
}
++index;
}
}
};
第二次做:
class Solution {
public:
/**
* 按照左右半区的方式重新组合单链表
* 输入:一个单链表的头节点head
* 将链表调整成题目要求的样子
*
* 后台的单链表节点类如下:
*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
void relocateList(struct ListNode* head) {
ListNode* p = head ;
int length = 0 ;
while ( p != NULL ) {
++ length ;
p = p -> next ;
}
vector<int> vec ;
p = head ;
for ( int i = 0; i < length; ++ i ) {
vec.push_back( p->val ) ;
p = p->next ;
}
p = head ;
int left_cur = 0 ;
int right_cur = length / 2 ;
int index = 0 ;
while( index < vec.size() - 1 && p != NULL ) {
if ( index % 2 == 0 ) {
p->val = vec[left_cur] ;
++ left_cur ;
}
else {
p->val = vec[right_cur] ;
++ right_cur ;
}
p = p->next ;
++ index ;
}
}
};
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。