java实现linkList翻转列表

首先是自定义node类


public class Node {

	private long data;
	private Node nextNode;
	
	public Node(long value)
	{
		this.data = value;
	}
	
	public long getData() {
		return data;
	}

	public void setData(long data) {
		this.data = data;
	}

	public Node getNextNode() {
		return nextNode;
	}

	public void setNextNode(Node nextNode) {
		this.nextNode = nextNode;
	}
	
}

然后头插法建立链表

public class linkList {

	private Node firstNode;//头结点
	
	public linkList()
	{
		firstNode = null;
	}
	
	/**
	 * 头插法建立链表
	 */
	public void insertBegin(long value)
	{
		Node node = new Node(value);
		if(firstNode == null)
		{
			firstNode = node;
		}
		else{
			node.setNextNode(firstNode);
			firstNode = node;
		}		
	}
}

同样,在linkList类中添加翻转列表的方法

        /**
	 * reverseList反转列表
	 */
	public Node  reverseList(){
		if(firstNode == null )
			return null;
		else if( firstNode.getNextNode() == null){
			return firstNode;
		}
		Node first = firstNode;
		Node second = firstNode.getNextNode();
		Node third = firstNode.getNextNode().getNextNode();
		
		first.setNextNode(null);
		while(third != null){
			second.setNextNode(first);
			first = second;
			second = third;
			third = third.getNextNode();
		}
		second.setNextNode(first);
		return second;
	}

打印反转后的列表

        //firstnode为列表翻转后的头结点
	public void printReverse(Node firstnode){
		if(firstnode== null)
		{
			System.out.println("链表为空");
			return;
		}
		Node currNode = firstnode;
		while(currNode != null)
		{
			System.out.print(currNode.getData()+" ");
			
			currNode = currNode.getNextNode();
			
		}
	}

 

你可能感兴趣的:(Java)