反转双链表

package com.harrison.class02;

import java.util.ArrayList;
import java.util.List;

public class Code02_ReverseDoubleList {
    
    
	public static class DoubleNode{
    
    
		public int value;
		public DoubleNode last;
		public DoubleNode next;
		
		public DoubleNode(int v) {
    
    
			this.value=v;
		}
	}
	
	public static DoubleNode reverseDoubleList(DoubleNode head) {
    
    
		DoubleNode pre=null;
		DoubleNode next=null;
		while(head!=null) {
    
    
			next=head.next;
			head.next=pre;
			head.last=next;
			pre=head;
			head=next;
		}
		return pre;
	}
	
	public static DoubleNode generateRandomDoubleList(int len,int value) {
    
    
		int size=(int)(Math.random()*(len+1));
		if(size==0) {
    
    
			return null;
		}
		size--;
		DoubleNode head=new DoubleNode((int)(Math.random()*(value+1)));
		DoubleNode pre=head;
		while(size!=0) {
    
    
			DoubleNode cur=new DoubleNode((int)(Math.random()*(value+1)));
			pre.next=cur;
			cur.last=pre;
			pre=cur;
			size--;
		}
		return head;
	}
	
	public static List<Integer> getDoubleListOriginOrder(DoubleNode head) {
    
    
		List<Integer> ans=new ArrayList<>();
		while(head!=null) {
    
    
			ans.add(head.value);
			head=head.next;
		}
		return ans;
	}
	
	public static boolean checkedLinkListReverse(List<Integer> origin,DoubleNode head) {
    
    
		DoubleNode end=null;
		for(int i=origin.size()-1; i>=0; i--) {
    
    
			if(!origin.get(i).equals(head.value)) {
    
    
				return false;
			}
			end=head;
			head=head.next;
		}
		for(int i=0; i<origin.size(); i++) {
    
    
			if(!origin.get(i).equals(end.value)) {
    
    
				return false;
			}
			end=end.last;
		}
		return true;
	}
	
	public static DoubleNode testReverseDoubleList(DoubleNode head) {
    
    
		if(head==null) {
    
    
			return null;
		}
		ArrayList<DoubleNode> list=new ArrayList<>();
		while(head!=null) {
    
    
			list.add(head);
			head=head.next;
		}
		list.get(0).next=null;
		DoubleNode pre=list.get(0);
		int N=list.size();
		for(int i=1; i<N; i++) {
    
    
			DoubleNode cur=list.get(i);
			cur.last=null;
			cur.next=pre;
			pre.last=cur;
			pre=cur;
		}
		return list.get(N-1);
	}
	
	public static void main(String[] args) {
    
    
		int testTimes=1000000;
		int len=100;
		int value=100;
		System.out.println("test begin");
		for(int i=0; i<testTimes; i++) {
    
    
			DoubleNode node1=generateRandomDoubleList(len, value);
			List<Integer> list1=getDoubleListOriginOrder(node1);
			node1=reverseDoubleList(node1);
			if(!checkedLinkListReverse(list1, node1)) {
    
    
				System.out.println("Oops");
			}
			
			DoubleNode node2=generateRandomDoubleList(len, value);
			List<Integer> list2=getDoubleListOriginOrder(node2);
			node2=testReverseDoubleList(node2);
			if(!checkedLinkListReverse(list2, node2)) {
    
    
				System.out.println("Oops");
			}
		}
		System.out.println("finish");
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44337241/article/details/121487232