剑指offer---15---反转链表

 
 
题意
输入一个链表,反转链表后,输出链表的所有元素。
 
 
分析
反转链表
 
 
 
代码 
/*
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 first = head;
        ListNode next = head.next;
        first.next = null;
        //保留这么一个状态:first及之前都是修改好的,next指向后面没修改过的。
        //进来先保存next的后面那些部分,将next去指向first
        while(next != null){
            ListNode temp = next.next;
            next.next = first;
            first = next;
            next = temp;
        }
        return first;
    }
}
原文地址:https://www.cnblogs.com/buptyuhanwen/p/9377051.html