前几天做了从尾到头打印链表元素的题目,以下链接是栈的方式输出。
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;
}
}