剑指offer15题

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

/**
 * 输入一个链表,反转链表后,输出新链表的表头。
 * 注意:编程时,首先判断非法条件
 * 思路:
 * 题目考的是递归
 * 1、记住下一个要处理的节点:next指针指向curr的next
 * 2、翻转指针:curr的next指向pre
 * 3、pre,curr一起往下一个节点移动
 * 4、重复
 */
public class Solution15 {
    public ListNode ReverseList(ListNode head) {
        //1、首先处理非法条件
        if (head == null||head.next == null){
            return head;
        }
        ListNode preNode = head;
        ListNode currNode = head.next;
        //注意,如果不写会造成死循环
        preNode.next = null;
        ListNode nextNode;
        while (null != currNode){
            nextNode = currNode.next;
            currNode.next = preNode;
            preNode = currNode;
            currNode = nextNode;
        }
        return preNode;
    }
}

 

posted @ 2020-08-08 15:57  Adom_ye  阅读(55)  评论(0编辑  收藏  举报