重排链表

我告诉自己,自己写的这个一定要记录下来,,,不为别的,只是因为我太憨了。这个题我一开始的想法,是根据这一条链表,反转新建一条新链表,然后两个开始遍历,结果后来发现,在反转的时候head这个链表就已经发生改变了,虽然我ListNode op = head,但是这个op还是在操作head。并没有重新建一个新链表。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reorderList(ListNode head) {
        ListNode ophead = null;
        ListNode cur = head;
        while(ophead != null){
            ListNode temp = cur.next;
            cur.next = ophead;
            ophead = cur;
            cur = temp;
        }
        ListNode newhead = head;
        while(newhead != ophead && newhead.next != ophead){
            ListNode temp = ophead;
            temp.next = newhead.next;
            newhead.next = temp;

            newhead = newhead.next.next;
            ophead = ophead.next;
        }
        ophead.next = null;
        return head;
    }
}

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        ListNode res = new ListNode(0);
        res.next = head;
        ListNode slow = res;
        ListNode fast = res;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode ophead = slow.next;
        slow.next = null;
        //断前链
        ListNode pre = null;
        ListNode cur = ophead;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        while(pre != null){

            ListNode leftNode = head.next;
            ListNode rigthNod = pre.next;
            pre.next = head.next;
            head.next = pre;
            pre = rigthNod;
            head = leftNode;
        }
    }
}

思路就是,切割主链表,然后反转后面的链表然后向主链表开始拼接。

主要难点就是切割主链表。从哪里开始切

以后命名一定要严格,我因为自己的命名再回头纠错的时候就蒙了,然后反复调试,就是不行,半个小时,其实一开始方向是对的,但是把自己绕晕了,就觉得自己的方法错了

重排链表

上一篇:Git的安装和初次配置以连接github,和在第三方程序(软件)中使用git 命令


下一篇:分布式事务的解决方案