您的位置:首页 > 职场人生

剑指offer - 面试题5:从尾到头打印链表

2016-09-20 00:00 549 查看
问题导读:

在不改变链表的结构的情况下,从尾到头打印链表

注:Java 实现

代码:

public class link {
//指针节点
public static class ListNode {
public Object data;
public ListNode next;
}
public static void printListReverse(ListNode pHead) {
/*
* 1.本解法是‘递归’算法
* 2.也可以使用栈,先将节点入栈,再一个一个返回
*/
if(pHead != null) {
if(pHead.next != null) {
printListReverse(pHead.next);
}
System.out.print(pHead.data + " ");
}
}
public static void main(String []args) {
//创建链表
int []arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
ListNode pHead = new ListNode();
pHead.next = null;
ListNode pNode = pHead;
for(int i = 0; i<arr.length; i++) {
ListNode pNew = new ListNode();
pNew.data = arr[i];
pNew.next = null;
pNode.next = pNew;
pNode = pNode.next;
}
//从尾到头输出链表
printListReverse(pHead.next);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: