• 143. Reorder List


    先找中点.. 1 2 3 4 5 6 7 8
    后半部分反转.. 1 2 3 4 8 7 6 5
    分别链接。。 1 8 2 7 3 6 4 5

    这种题思路不难,但是操作起来比较繁琐,每次做完一堆变量。

    想不用这么多变量,就要用P1 P2这种名字上毫无意义的指针。。否则会误导善良,天真,无暇,无辜的群众。

    public class Solution 
    {
        public void reorderList(ListNode head) 
        {
            if(head == null || head.next == null || head.next.next == null) return;
            
            ListNode slow = head;
            ListNode fast = head;
            while(fast.next != null && fast.next.next != null)
            {
                slow = slow.next;
                fast = fast.next.next;
            }
            
    
            ListNode temp = slow.next;
            slow.next = null;
    
            
            ListNode dummy = new ListNode(666);
            dummy.next = temp;
            ListNode prev = dummy;
            ListNode next = temp.next;
            
    
            
            temp.next = null;
            while(next != null)
            {
                prev = temp;
                temp = next;
                next = next.next;
                temp.next = prev;
            }
            
            
            ListNode temp1 = head;
            ListNode temp2 = temp;
    
            
            
            while(temp2 != null)
            {
                ListNode cur1 = temp1.next;
                temp1.next = temp2;
                temp1 = cur1;
                
                ListNode cur2 = temp2.next;
                temp2.next = temp1;
                temp2 = cur2;
            }
            
            
            
            head = dummy.next;
            
            
        }
    }
    

    Leetcode好像挂了,几个TEST跑了好久。

  • 相关阅读:
    spoj705
    bzoj2440
    spoj220
    bzoj2301
    hdu1695
    poj3294
    hdu3518
    poj3693
    函数
    样式
  • 原文地址:https://www.cnblogs.com/reboot329/p/5874370.html
Copyright © 2020-2023  润新知