链表(拆分,反转,合并)

题目描述

 

Given a singly linked list LL 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.

package xidian.lili.haoweilai;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
		next = null;
	}
}

public class Demo01 {
	public void reorderList(ListNode head) {
		if(head==null || head.next==null){
			return;
		}
		ListNode fast=head;
		ListNode slow=head;
		while(fast.next!=null && fast.next.next!=null){
			slow=slow.next;
			fast=fast.next.next;
		}
		ListNode after=slow.next;//后半部分链表
		slow.next=null;//断开
		//反转链表
		ListNode pre=null;
		while(after!=null){
			ListNode temp=after.next;//保存当前节点的下一个节点
			after.next=pre;
			pre=after;
			after=temp;
		}
		//合并两条链表
		ListNode first=head;
		after=pre;
		while(first!=null && after!=null){
			ListNode ftemp=first.next;
			ListNode atemp=after.next;
			first.next=after;
			after.next=ftemp;
			after=after.next;
			first=ftemp;
			after=atemp;
		}

	}
}

 

你可能感兴趣的:(算法--链表)