题解 | #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

昨天又想到一种方法,用指针去做,时间复杂度:O(链表长度)

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        
        ListNode cur = null;
        ListNode next = null;
        ListNode root = null;
        
        if(head == null || head.next == null){
            return head;
        }
        
        cur = head;
        next = cur.next;
        
        do{
            cur.next = root;
            root = cur;
            cur = next;
            next = next.next;
        }while(next != null);
        
        cur.next = root;
        
        return cur;
        
        
        
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务