LeetCode 解题报告 Reorder List

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,

Given {1,2,3,4}, reorder it to {1,4,2,3}.

分析:

如果题目没有要求,可以用栈来存储链表后半段的结点,然后依次弹出往前插入链表,但是题目要求不能申请新空间来改变原来结点的值。

一开始我想到了一个时间是O(n),空间是O(1)的方法,就是首先找到中间结点,然后定位中间结点的前后两个结点,把next结点插入到prev结点之后,然后next向后指,prev结点向前指,刚要为我的想法高兴的时候,忽然发现,如果想让prev往前指,就必须得存储,或者每次遍历,所以这种思路是行不通的。

还是老老实实的先把后半段链表进行翻转,然后合并两个链表吧,这样的时间复杂度也是O(n),空间是O(1)

public class ReorderList {
	public void reorderList(ListNode head) {
        if(head == null)
        	return ;
        ListNode node = head;
        ListNode midPre = FindMidPre(node);
        ListNode midNode = midPre.next;
        
        //将链表从中间断开
        midPre.next = null;
        //反转后半段链表
        ListNode ReverseListHeadNode = Reverse(midNode);
        //合并两个链表
        ListNode h1 = head;
        ListNode h2 = ReverseListHeadNode;
        MergeList(h1,h2);
    }
	
	public void MergeList(ListNode h1,ListNode h2){
		ListNode curr = h1;
		while(curr.next != null){
			ListNode temp = curr.next;
			curr.next = h2;
			h2 = h2.next;
			curr.next.next = temp;
			curr = temp;
		}
		curr.next = h2;
	}
	public ListNode Reverse(ListNode head){
		if(head == null || head.next == null)
			return head;
		ListNode prev = head;
		ListNode curr = prev.next;
		ListNode next = curr.next;
		while(next != null){
			curr.next = prev;
			prev = curr;
			curr = next;
			next = next.next;
		}
		curr.next = prev;
		head.next = null;
		return curr;
	}
	public ListNode FindMidPre(ListNode head){
		ListNode node = head;
		ListNode slow = node,fast = node;
		ListNode result = head;
		while(fast != null && fast.next != null){
			result = slow;
			slow = slow.next;
			fast = fast.next.next;
		}
		return result;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值