前几天做了从尾到头打印链表元素的题目,以下链接是栈的方式输出。
http://blog.youkuaiyun.com/quentain/article/details/50906099
本题还有递归的方法,补充下递归的方法。
递归解法:
public class Solution {
ArrayList<Integer> arrayList=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}
题目描述
输入一个链表,反转链表后,输出链表的所有元素。
本题是采用指针的方法
在线代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
ListNode next = null;
ListNode pre=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}

本文介绍了一种使用递归方法实现链表元素从尾到头的打印,并提供了一个利用指针操作来反转链表的解决方案。通过这两种方法的学习,可以加深对链表这一数据结构的理解。
499

被折叠的 条评论
为什么被折叠?



