15、反转链表(循环和递归两种方式)

题目描述
输入一个链表,反转链表后,输出链表的所有元素。

leetcode上有详细说明

迭代法

/*
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 newHead = null;
        ListNode tmp = null;
        while(head!=null){
            tmp = newHead;
            newHead = head;
            head = head.next;
            newHead.next = tmp;
        }
        return newHead;
    }
}

递归法:

/*
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 || head.next==null){
            return head;
        }
        ListNode p = ReverseList(head.next);
        head.next.next = head;  
        head.next = null;
        return p;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容