smilevchy's blog

Life & Study & Chasing

Leetcode_Reorder List

原题链接: https://oj.leetcode.com/problems/reorder-list/

正是这道题,让我知道了有 “快慢指针” 这种好东西。以前每当要做类似遍历链表的操作时,比如取中点,总是先遍历完一遍链表来获得长度,求得中点再遍历一次,实在是不雅观。而通过 “快慢指针”,只要写一次遍历就可以拿到中点。

public void reorderList(ListNode head) {
    if (head == null || head.next == null) {
        return;
    }

    ListNode slowCursor = head;
    ListNode quickCursor = head;

    while (quickCursor != null && quickCursor.next != null && quickCursor.next.next != null && slowCursor != null && slowCursor.next != null) {
        slowCursor = slowCursor.next;
        quickCursor = quickCursor.next.next;
    }

    ListNode head1 = head;
    ListNode head2 = slowCursor.next;

    head2 = reverseList(head2);

    while (head1 != null && head2 != null) {
        ListNode head2Next = head2.next;
        head2.next = head1.next;
        head1.next = head2;
        head1 = head2.next;
        head2 = head2Next;

        if (head2 == null) {
            head1.next = null;
        }
    }
}

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode cursor = head;
    ListNode next = null;

    while (cursor != null) {
        next = cursor.next;
        cursor.next = prev;
        prev = cursor;
        cursor = next;
    }

    return prev;
}

Today’s Understanding

在设计模块接口时,入口参数绝对要设计成数值形式啊,之前居然设计成了字符串形式,由于有其他模块也调用到,现在造成的局面就是根本没有扩展性,而且要修改的话还要让其他调用模块也进行相应修改。

悲剧……

Today’s Understanding

今天重构几个月前的代码过程中,感觉到种种阻力。 原因在于代码的耦合度过高,信息过于具体、过于分散,导致修改一处代码时,常常要联动修改很多处地方。

感悟一:代码还是抽象化程度高一点才好。

现在写代码的感觉比以前好一点,以前只会堆砌功能,不懂得整体架构设计,写出来的代码可以说是存在于 ”开发时“。 现在开始有意识注意整体的设计,代码的可阅读性,力求让代码不仅存在于”开发时“,也存在于”阅读时“、”维护时“。

感悟二:像写作文一样写代码,让非代码作者阅读时就像在读一篇文章一样,有整体架构,有段落意思,尽量让代码的内涵浮出海平面。