题目

将链表反转输出

解决思路如下:

创建两个链表,pre指向当前结点的上一个结点,next指向当前结点的下一个结点,遍历整个链表,将链表进行反转

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

题目来源:牛客网

更好的解析:https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13