LeetCode学习之反转输出链表

 

import org.junit.Test;

import java.util.List;

public class ReverseListNode {

    public static void main(String[] args) {
        ListNode[] reverselist = new ListNode[5];
        for (int i = 0; i < 5; i++) {
            reverselist[i] = new ListNode();
            reverselist[i].val = i;
        }//必须初始化完了再进行链表的链接,不然链接为空
        for (int i = 0; i < 5; i++) {
            if (i == 0) {
                reverselist[i].head = null;
            } else {
                reverselist[i].head = reverselist[i - 1];
            }
            if (i == 4) {
                reverselist[i].next = null;
            } else {
                reverselist[i].next = reverselist[i + 1];
            }
        }

        ListNode reverse = reverseList(reverselist[0]);
        System.out.println(reverse);
        while (reverse != null) {
            System.out.println(reverse.val);
            reverse = reverse.next;
        }
    }

    public static ListNode reverseList(ListNode head) {
        /* //双指针
        ListNode left;
        ListNode right;
        ListNode temp;
        left = head;
        right = null;
        while (left != null) {
            temp = left.next;
            left.next = right;
            right = left;
            left = temp;
        }
        return right;
        */
        ListNode temp = recursionListNode(head, null);
        return temp;

    }
    /*递归求链表尾,然后返回的每一层翻转指针指向。
    //最后一层current为空,返回previous即尾结点,上一层的current即返回的previous

    0          1          2          3          4          null
                                             previous     current
    //递归后层层将current.next指向previous即可。
    0          1          2          3          4          null
                                  previous   current
    0          1          2          3          4          null
                       previous   current
    */
    private static ListNode recursionListNode(ListNode current, ListNode previous) {
        if (current == null) {
            return previous;
        }
        ListNode recursiontemp = recursionListNode(current.next, current);
        current.next = previous;
        return recursiontemp;
    }

}

class ListNode {
    int val;
    ListNode head;
    ListNode next;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值