逆置鏈表中的一段

package com.zuochengyun.book.chaptertwo.list;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 反轉一個鏈表的一段       
 * @author 
 *
 */
public class ListRevertNToN {
	
	private static Node doRevertListNFromN(Node head,int from, int to) {
		if(head==null || from < 0 || to < from) {
			return null;
		}
		if(to==from) {
			return head;
		}
		//新建一個head 方便操作
		Node myHead=new Node(0);
		myHead.next=head;
		Node currentNode=myHead;
		int index=0;
		Node firstEnd=null;
		Node secondHead=null;
		//要逆置list其中的一段,可以把鏈表看成三段
		while(currentNode !=null) {
			//記錄第一段最後一個結點
			if(index==from-1) {
				firstEnd=currentNode;
			}
			//獲取最後一段的開頭
			if(index == to+1) {
				secondHead=currentNode;
				break;
			}
			index++;
			currentNode=currentNode.next;
		}
		if(to >= index) {
			return null;
		}
		//第一段和第二段開頭連接好
		firstEnd.next=doPartRevert(firstEnd.next, secondHead);
		return myHead.next;
	}
	/*
	 * 逆置第二段鏈表,並且和第三段鏈表連接好
	 */
	private static Node doPartRevert(Node begin,Node end) {
		Node pre=end;
		Node next=begin;
		while(next!=null && next!=end) {
			next=begin.next;
			begin.next=pre;
			pre=begin;
			begin=next;
		}
		return pre;
	}
	private static Node doRevert(Node head) {
		Node pre = null;
		Node next = head;
		while(next != null) {
			next = head.next;
			head.next= pre;
			pre = head;
			head=next;
		}
		return pre;
	}
	public static void main(String[] args) {
		Node head=doRevertListNFromN(MyListUtils.cteateSigleList(), 2, 3);
		//輸出鏈表
		MyListUtils.printList(head);
	}
}

 

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