题目:
输入一个链表,从尾到头打印链表每个节点的值
方法一:
将容器printListFromTailToHead中的内容塞入栈reverse中,在将栈中的元素依次存入顺序容器result,并打印出来,实现将元素从尾到头到打印,由于栈是先进后出到,所以保存进栈中再取出时就可以实现元素顺序到翻转
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector <int> result;
if(head==NULL)
return result;
stack<ListNode*> reverse;
ListNode* node=head;
while(node!=NULL)
{
reverse.push(node);
node=node->next;
}
while(!reverse.empty())
{
node=reverse.top();
cout<<node->val;
result.push_back(node->val);
reverse.pop();
}
return result;
}
};
方法二:链表到原地逆转
使用三个变量控制,buf表示当前值,buf->next表示翻转之后的下一个值,head->next表示下一个要处理的值,经过处理的元素,按照元素buf顺序访问,得到的就是翻转之后的序列
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> vec;
ListNode *buf=head;
ListNode *pre=buf;
if(head==NULL)
return vec;
while(head->next!=NULL)
{
buf=head->next;
head->next=buf->next;
buf->next=pre;
pre=buf;
}
while(buf)
{
vec.push_back(buf->val);
buf=buf->next;
}
return vec;
}
};
用三个指针 pre, cur, next 实现原地翻转
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if (head == NULL) return res;
if (head -> next == NULL) {
res.push_back(head -> val);
return res;
}
ListNode *pre = NULL, *cur = head, *next = head -> next;
while(next != NULL) {
cur -> next = pre;
pre = cur;
cur = next;
next = cur -> next;
}
cur -> next = pre;
while(cur != NULL) {
res.push_back(cur->val);
cur = cur->next;
}
return res;
}
};
或者
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>res;
if(head == NULL)
return res;
ListNode* pre = NULL;
ListNode* cur = head;
while(cur != NULL){
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
for( ;pre != NULL; pre = pre->next)
res.push_back(pre->val);
return res;
}
};