java如何给一个链表定义和传值_阿里面试题详解:如何实现一个高效的单向链表逆序输出?...

acf014d8e3596a9308cbc95580869b95.png

问题:如何实现一个高效的单向链表逆序输出?

出题人:阿里巴巴出题专家:昀龙/阿里云弹性人工智能负责人

参考答案:下面是其中一种写法,也可以有不同的写法,比如递归等。供参考。

typedef struct node{
    int           data;
    struct node*  next;
    node(int d):data(d), next(NULL){}
}node;

void reverse(node* head)
{
    if(head == NULL){
        return;
    }

    node* pleft = NULL;
    node* pcurrent = head;
    node* pright = head->next;

    while(pright){
        pcurrent->next = pleft;
        node *ptemp = pright->next;
        pright->next = pcurrent;
        pleft = pcurrent;
        pcurrent = pright;
        pright = ptemp;
    }

    while(pcurrent != NULL){
        cout<< pcurrent->data << "t";
        pcurrent = pcurrent->next;
    }
}
class Solution<T> {

    public void reverse(ListNode<T> head) {
       if (head == null || head.next == null) {
    	   return ;
       }
       ListNode<T> currentNode = head;
       Stack<ListNode<T>> stack = new Stack<>();
       while (currentNode != null) {
    	   stack.push(currentNode);
    	   ListNode<T> tempNode = currentNode.next;
    	   currentNode.next = null; // 断开连接
    	   currentNode = tempNode;
       }
       
       head = stack.pop();
       currentNode = head;
       
       while (!stack.isEmpty()) {
    	   currentNode.next = stack.pop();
    	   currentNode = currentNode.next;
       }
    }
}

class ListNode<T>{
	T val;
	public ListNode(T val) {
		this.val = val;
	}
	ListNode<T> next;
}

资料分享

小编整理了设计模式和算法两个面试较难的专题资料,希望能给算法和设计模式还需提高的同学提供帮助。

数据结构和算法专题资料截图

f9438aa1ad7939d854cf061333dc0de5.png

设计模式面试专题资料截图

12283e89e310bcf1d55555f565e30b19.png

免费资料领取方式一:关注+转发+私信**算法** 即可前往领取免费资料领取方式二:

Android架构视频+面试专题文档+学习笔记​shimo.im
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值