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;
    }
}

你可能感兴趣的