LeetCode 143
Reorder List
Problem Description:
将链表中的值按照“一个头一个尾”的顺序输出,即若链表为1-2-3-4-5,输出结果为1-5-2-4-3.
具体的题目信息:
https://leetcode.com/problems/reorder-list/description/Solution:
- 解题思路:遍历一遍链表将链表中的值存储起来,再按照一定的顺序构造新链表。
- 编程实现:用
vector
数组顺序存储链表中所有的值,然后按照一头一尾的顺序访问数组,将每次访问的值push进final_num
栈中,然后将栈中元素依次插入链表的head后面。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if (head == NULL)
return;
if (head->next == NULL)
return;
ListNode* p = head;
vector<int> num;
while(p) {
num.push_back(p->val);
p = p->next;
}
stack<int> final_num;
for (int i = 0; i < num.size()/2; i++) {
if (i != 0)
final_num.push(num[i]);
int j = num.size()-i-1;
final_num.push(num[j]);
}
if (num.size()%2 == 1) {
final_num.push(num[num.size()/2]);
}
ListNode* temp = new ListNode(final_num.top());
temp->next = head->next;
head->next = temp;
temp->next = NULL;
final_num.pop();
ListNode* q;
while(!final_num.empty()) {
q = new ListNode(final_num.top());
final_num.pop();
q->next = temp;
head->next = q;
temp = q;
}
return;
}
};