从尾到头打印链表
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
// 节点
struct ListNode {
int val;
struct ListNode *next;
};
std::vector<int> printListFromTailToHead(ListNode* head) {
std::vector<int> vect;
vect.clear();
if (head == NULL) {
return vect;
}
ListNode* nextNode = head->next;
// 反转单向链表
while (nextNode->next != NULL) {
ListNode* temp = nextNode->next;
nextNode->next = nextNode->next->next;
temp->next = head->next;
head->next = temp;
}
// 遍历单向链表
nextNode = head->next;
while (nextNode != NULL) {
vect.push_back(nextNode->val);
nextNode = nextNode->next;
}
vect.push_back(head->val);
return vect;
}
测试