从尾到头打印链表

本文介绍了一种不改变链表结构的情况下逆序打印链表的方法,利用栈的特性实现链表元素的逆序输出,并提供了两种实现方式:迭代法和递归法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先想到是改变链表结构,使其从尾指向头

逆序链表:

 ListNode* ListReverse(ListNode *head){
    if(head==NULL||head->next==NULL) return head;
    ListNode *p->next=head;
    ListNode *current,*pre=head;
    current=pre->next;
    while(current){
    pre->next=current->next;
    current->next=p->next;
    p->next=current;
    current=pre->next;
    }
    return p->next;
}


但是当面试官不允许改变链表结构时,我们通过仔细理解题目,

从头到尾打印链表,意味着先进后出,所以可以使用栈结构

vector<int> ListReverse(ListNode *head){

    std::stack<ListNode*> s;

    vector<int> res;

    if(head==NULL) return res;

    ListNode *p=head;   

    if(p!=NULL){

      s.push(p);

      p=p->next;

     }

     while(!s.empty()){

      p=s.top();

      res.push_back(p->val);

      s.pop();

     }

     return res;}

既然想到了用栈来实现,而递归本质上也是一种栈

 vector<int> ListReverse(ListNode *head){

    vector<int> res;

    if(head==NULL) return res;

    ListNode *p=head;

    if(p){

      if(p->next)

          ListReverse(p->next);

      res.push_back(p->val);

     }

     return res;

  }




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值