鏈表(拆分,反轉,合併)

題目描述

 

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;
		}

	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章