题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
首先确定题意就是通过接到的链表进行一个倒置,那么很显然就是通过建立新链表,用倒插法的方法的效率是最高的,复杂度是O(1),代码如下:
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode tail=null;
        while (head!=null){
            ListNode tempListNode=new ListNode(head.val);
            tempListNode.next=tail;
            tail=tempListNode;
            head=head.next;
        }
        return tail;
    }
}
public class test01{
    public static void main(String[] args) {
        Solution solution=new Solution();
        ListNode head=new ListNode(0);
        ListNode tail=head;
        for (int i = 1; i <= 3; i++) {
            tail.val=i;
            if (i!=3)
                tail.next = new ListNode(0);
                tail=tail.next;
        }
        head.display(head);
        ListNode node = solution.reverseList(head);
        System.out.println("排序后");
        head.display(node);
    }
}
查看16道真题和解析
