leetcode之reorder-list

题目描述


Given a singly linked list L: L0L1→…→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}.

代码

第一种:

三步走:

1.找到中间节点;

2.反转后半部分的节点(即中间节点之后的所有节点);

3.将两部分节点合并

代码:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public reorderList(ListNode head){if(head==null)return head;ListNode slow=head;ListNode fast=head;while(fast.next!=null&&fast.next.next!=null){fast=fast.next.next;slow=slow.next;}ListNode next=slow.next;if(next!=null&&next.next!=null){ListNode pre=next.next;while(pre!=null){
//保存下一节点
  next.next=pre.next;
//pre节点插在slow节点之后,slow节点保持不动
 pre.next=next;slow.next=pre;
//更新pre节点
 pre=next.next;}merge(head,slow);}public void merge(ListNode head,ListNode slow){ListNode p=head;ListNode q=slow.next;while(q!=null&&p!=null){ //保存q的下一个节点
slow.next=q.next;
//将q插在p节点之后,尾插法
 q.next=p.next;p.next=q;
//更新p、q节点
 q=slow.next;p=p.next.next;}}}




第二种:

1.找到中间节点;

2.将后半部分节点入栈(出栈顺序与入栈顺序相反,所以一入一出就完成了链表后半部分的反转);

3.节点依次出栈,与入栈顺序相反,然后隔一个插入到前半部分中.

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.Stack;
public class Solution {
    public void reorderList(ListNode head) {
		if(head==null)return;
        ListNode fast=head,slow=head;
        while(fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
       Stack<ListNode> stack=new Stack<ListNode>();
       ListNode p=slow.next;
        while(p!=null){
            stack.push(p);
            p=p.next;
        }
        slow.next=null;
        ListNode cur=head;
        while(cur!=null&&!stack.isEmpty()){
            ListNode next=cur.next;
            cur.next=stack.pop();
            cur.next.next=next;
            cur=next;
        }
    }
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值