19反转链表--剑指offer,java版

19反转链表–剑指offer,java版

题目描述
输入一个链表,反转链表后,输出新链表的表头。
我们需调整链表中指针的方向。但注意调整指针方向时,除了要知道节点本身,节点的前一个节点外,还要事先保存节点的后一个节点,以防止节点断开后,找不到后面这个节点

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pReversed = null; //反转后链表的头节点
        ListNode pNode = head; //当前节点
        ListNode pPre = null; //前一个节点
        while(pNode != null){
            ListNode pNext = pNode.next; //后一个节点
            if(pNext == null){
                pReversed = pNode;
            }
            pNode.next = pPre;
            pPre = pNode;
            pNode = pNext;
        }
        return pReversed;
    }
}

你可能感兴趣的:(剑指offer)