链表反转 java实现

即将0-->1-->2-->3-->4-->5-->6-->7-->8-->9

反转为:9-->8-->7-->6-->5-->4-->3-->2-->1-->0

package com.kiruma.test;

public class reverse {
	
	static class Node{
		public int value;
		public Node next;
		public Node(int value){
			this.value=value;
		}	
	}
	static Node init(){
		Node head=null;
		Node p=null;
		for(int i=0;i<10;i++){
			Node node=new Node(i);
			if(i==0){
				head=node;
				p=node;
			}else{
			p.next=node;
			p=node;
			}
		}
		return head;
	}
	static Node reverse(Node head){
		Node p1,p2,p3;
		p1=head;
		p2=p1.next;
		p3=p2.next;
		p1.next=null;
		while(true){
			if(p3.next==null){
				p2.next=p1;
				p3.next=p2;
				head=p3;
				break;
			}else{
				p2.next=p1;
				p1=p2;
				p2=p3;
				p3=p3.next;
				p2.next=p1;
				
			}
			
		}
		return head;
	
	}
	static void printNode(Node p){
		while(p!=null){
			if(p.next==null){
				System.out.print(p.value);
			}else{
				System.out.print(p.value+"-->");
			}
			p=p.next;
		}
	}
	public static void main(String[] args){
		Node head=init();
		printNode(head);
		System.out.println("\n----反转之后----");
		Node p=reverse(head);
		printNode(p);
		
	}
}

结果:


猜你喜欢

转载自blog.csdn.net/qq_34761108/article/details/79521763