leedcode做题总结,题目Reorder List 13/11/12

题目很简单,把12345重新排序成15243.

方法是把愿链表打进栈里,同时记录下节点的个数

之后从栈中弹出一个插入原链表中。



public static void reorderList(ListNode head) {
        if (head!=null) {
            Stack<ListNode> s = new Stack<ListNode>();
            int num = 0;
            ListNode h = head;
            ListNode p = head;

            while (true) {
                s.push(p);
                num++;
                if (p.next != null) {
                    p = p.next;
                } else break;

            }
            int num2=num;
            int jo=num%2;

            num = num / 2;
            if(jo==0)num=num--;
            ListNode t=null;
            for (int i = 0; i < num; i++) {
                t = s.pop();
                t.next = h.next;
                h.next = t;
                h = t.next;
            }
            //if(jo==0) t.next=null;
            p=head;

            for (int i = 0; i <num2-1; i++) {
                p = p.next;
            }
            p.next=null;

            //for testing
            p=head;

            for (int i = 0; i <6; i++) {


                System.out.println(p.val);
                if (p.next != null) {
                    p = p.next;
                } else break;

            }
        }


    }


Update:2015/08/15

这道题上面的解法不是很好,因为用到了额外的栈,而原题是要求使用in place,所以不应该使用栈。更好的解法是分三步,第一步找到中间节点(快慢指针),第二步是反转下半段,第三部是将前半段和反转后的后半段进行merge。

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: void
     */

    public void reorderList(ListNode head) {  
        // write your code here
        
        if (head != null && head.next != null) {
			ListNode slow = head;
			ListNode fast = head;
 
			while (fast != null && fast.next != null) {
				slow = slow.next;
				fast = fast.next.next;
			}
 
			ListNode second = slow.next;
			slow.next = null;
			
			if (second != null && second.next != null) {
    		    ListNode pre = second;
    		    ListNode curr = second.next;
        		while (curr != null) {
        			ListNode temp = curr.next;
        			curr.next = pre;
        			pre = curr;
        			curr = temp;
        		}
    		    second.next = null;
                second = pre;
			}
			
			ListNode p1 = head;
			ListNode p2 = second;

			while (p2 != null) {
				ListNode tmp = p2.next;
                p2.next = p1.next;		
				p1.next = p2;
				p1 = p1.next.next;
				p2 = tmp;
			}
		}
        
    }
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值