题目:
输入一个链表的头结点,从尾到头反过来打印每个结点的值。
链表结点定义:
struct ListNode{int value;ListNode* pNext;
};
思路:
1、改变链表结构的话,先反转链表,然后从头到尾打印每个结点的值。(后续博文会有相关实现,这里就暂不实现)
2、无需改变链表结构,使用栈,遍历整个链表,将结点依次入栈,然后再依次出栈,实现“后进先出”。
3、无需改变链表结构,递归实现,如果链表结点数过多的话,可能会导致栈溢出。
代码:
void PrintListReversingly_Iteratively(ListNode* pHead){std::stack<ListNode*> nodes;ListNode* pNode=pHead;while(pNode!=NULL){nodes.push(pNode);pNode=pNode->pNext;}while(!nodes.empty()){pNode=nodes.top();cout<<pNode->value<<"\t";nodes.pop();}cout<<endl;
}void PrintListReversingly_Recursively_1(ListNode* pHead){if(pHead==NULL)return;PrintListReversingly_Recursively_1(pHead->pNext);cout<<pHead->value<<"\t";
}void PrintListReversingly_Recursively_2(ListNode* pHead){if(pHead!=NULL){if(pHead->pNext!=NULL)PrintListReversingly_Recursively_2(pHead->pNext);cout<<pHead->value<<"\t";}
}
在线测试OJ:
http://www.nowcoder.com/books/coding-interviews/d0267f7f55b3412ba93bd35cfa8e8035?rp=1
AC代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:void printList(ListNode* head,vector<int> &nodes){if(head!=NULL){printList(head->next,nodes);nodes.push_back(head->val);}return;}vector<int> printListFromTailToHead(struct ListNode* head) {vector<int> nodes;printList(head,nodes);return nodes;}
};
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:vector<int> printListFromTailToHead(struct ListNode* head) {vector<int> nodes;while(head!=NULL){nodes.push_back(head->val);head=head->next;}reverse(nodes.begin(),nodes.end());return nodes;}
};