【追求进步】反转链表

来源:互联网 发布:产业链分析理论 知乎 编辑:程序博客网 时间:2024/04/30 18:57

前几天做了从尾到头打印链表元素的题目,以下链接是栈的方式输出。

http://blog.csdn.net/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;    }}



0 0
原创粉丝点击