【剑指offer】反转链表

反转链表

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

今年秋招第一次面试,小米后端研发问了这个问题,当时真的是脑袋晕啊,一点面试技巧都不懂...
以自己的实力,这种题目轻轻松松撕了...

维护三个指针左、中、右,边向后移动,边改变指针指向的方向。

/*
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 l = head, m = head.next, r; // 左节点、中节点、右节点
        head.next = null;
        while (m != null) {
            r = m.next;
            m.next = l;
            l = m;
            m = r;
        }
        return l;
    }
}
全部评论

相关推荐

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