首页 > 试题广场 >

从尾到头输出链表 题目:输入一个链表的头结点,从尾到头反过来

[问答题]

从尾到头输出链表
题目:输入一个链表的头结点,从尾到头反过来输出每个结点的值。链表结点定义如下:

struct ListNode
{
    int  m_nKey;
    ListNode *m_pNext;
};


推荐
xxj头像 xxj
可以有两个方法:如果可以破坏链表m_pNext,那可以一个循环将所有m_pNext指向上一个接点,然后一个循环输出,然后再还原接点。
个人觉得这个太复杂。
方法二:使用递归或借助栈来做。(所有递归都可以通过栈来转成非递归)

void PutRlist(const listNode * pNode)
{
    if(!pNode) return;
    PutRlist(pNode->m_pNext);
    //输出。
    std::cout<<pNode->m_nKey<< "<-";
}
编辑于 2015-02-05 09:49:51 回复(0)
#include <iostream>
#include <stack>
using namespace std;

void PrintlistReverse(listNode *pHead)
{
    stack<ListNode *> nodes;
    ListNode *pNode = pHead;
    while(pNode != NULL)
    {
       nodes.push(pNode);
       pNode = pNode->m_pNext;
    }
    while( !nodes.empty() )
    {
       nodes.top();
       cout << pNode->m_pNext << " ";
       nodes.pop();
    }
}

编辑于 2015-05-25 10:35:29 回复(2)
class ListNode {  
    int val;     
    ListNode next = null;      
    ListNode(int val) {         
        this.val = val;     
    } 
}
   
public class Solution {
  public ListNode ReverseList(ListNode head) {
   ListNode reversedHead = null;
   ListNode nodeNow = head; // 当前遍历的节点   
   ListNode prev = null; // 前一个节点
   ListNode next = null; // 下一个节点
   while (nodeNow != null) {
    next = nodeNow.next;
    if (next == null) { // 遍历到最后一个节点了
      reversedHead = nodeNow;  }
    nodeNow.next = prev;
    prev = nodeNow; //下一次遍历的时候prev和nodeNow都变化了
    nodeNow = next;
   }
   return reversedHead;
   }
 } 

编辑于 2015-09-16 14:04:05 回复(0)
#include<stack>
void PrintNode(ListNode *head){
    ListNode *p=head;
    stack<ListNode *> stacck0;
    while(p){
         stack0.push(p);
         p=p->m_pNext;
    }
    while(!stack0.empty())
    {
        cout<<stack0.top()->m_nKey<<" ";
        stack0.pop();
    }
} 

发表于 2016-06-24 10:58:33 回复(0)
void reversePrintList( ListNode * pHead)
{
    if(pHead == NULL)    return ;
    if( pHead->m_pNext != NULL)
       reversePrintList(phead->m_pNext)
    printf("%d\t",pHead->m_nKey);
}
发表于 2016-03-20 21:39:58 回复(0)

#include <stack>
#include <cstdlib>
#inlucde <iostream>

uisng namespace::std;
using std::stack;

void inverseOut(ListNode *head) {
    if (NULL == head) {
        return ;
    }
    
    stack<int> s;
    ListNode *p = head;
    while (p) {
        s.push(p->m_nKey);
        p = p->m_pNext;
    }

    while(!s.empty()) {
        ListNode *pNode = s.top();
        cout << pNode->m_nKey << endl;
        s.pop();
    }
    cout << endl;

    return ;
}

编辑于 2015-09-18 22:51:31 回复(0)
void reversePrint(ListNode *head) {
    stack<int> stk;
    ListNode *p  = head;
    while( p != NULL ) {
        stk.push(p->m_nKey);
        p = p->m_pNext;
    }
    while( !stk.empty() ){
        cout<<stk.top()<<endl;
        stk.pop();
    }
}
发表于 2014-12-21 16:55:21 回复(0)
分析:这是一道很有意思的面试题。该题以及它的变体经常出现在各大公司的面试、笔试题中。
发表于 2014-10-25 00:26:17 回复(0)
遍历链表,把每个结点的值压入栈中,直至全部压入,然后出栈输出结点值
发表于 2014-10-11 23:04:42 回复(0)