码迷,mamicode.com
首页 > 编程语言 > 详细

java实现链表

时间:2018-02-10 01:18:08      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:ack   nod   转型   ext   list   bar   两种方法   pac   station   

    今天和同学讨论时,他说java没有指针怎么实现链表。的确,在Java中没有指针。但是,Java中引用和C++中的引用有很大不同,而且具有一定指针的功能(过两天会总结)。所以,就在家用Java实现了一下链表这种数据结构。目前我想到了两种方法用Java实现链表:

        1、Java允许类的定义中出现该类对象,所以可以通过对该类对象的引用实现链表。

        2、可以通过定义一个基类,通过子类的向上转型。通过父类指针模拟C++中的指针类型,从而实现链表。

废话不多说,上代码:

    方法1 Node.java:

package com.pasilo;

public class Node {
	
	private int data;
	private Node next;
	
	public Node(){}
	
	public Node(int data){
		this.data = data;
		this.next = new Node();
	}
	
	public int getData(){
		return this.data;
	}
	
	public void setData(int value){
		this.data = value;
	}
	
	public Node getNext(){
		return this.next;
	}
	
	public void setNewNext(int value){
		Node newNode = new Node(value);
		this.next = newNode;
	}
	
	public void setNext(Node node){
		this.next = node;
	}
}

    方法1 List.java:

package com.pasilo;

public class List {
	
	private Node head;
	private Node current;
	
	public List(int data){
		this.head = new Node(data);
		current = head;
	}
	
	public void append(int value){
		current.setNewNext(value);
		current = current.getNext();
	}
	
	public void remove(int destation){
		Node pointer = this.head;
		for(int i=0;i<destation-1;i++){
			pointer = pointer.getNext();
		}
		Node temp = pointer.getNext().getNext();
		pointer.setNext(temp);
	}
	
	public void insert(int destation,int value){
		Node pointer = this.head;
		for(int i=0;i<destation-1;i++){
			pointer = pointer.getNext();
		}
		Node temp = pointer.getNext();
		Node newNode = new Node(value);
		pointer.setNext(newNode);
		newNode.setNext(temp);
	}
	
	public int at(int index){
		Node pointer = this.head;
		for(int i=0;i<index;i++){
			pointer = pointer.getNext();
		}
		return pointer.getData();
	}
	
	public void display(){
		Node pointer = this.head;
		while(current != pointer){
			System.out.println("data is:"+pointer.getData());
			pointer = pointer.getNext();
		}
		System.out.println("data is:"+pointer.getData());
		System.out.println("this is the end.");
	}
	
	public int size(){
		int size = 1;
		Node pointer = this.head;
		while(current != pointer){
			pointer = pointer.getNext();
			size++;
		}
		return size;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List list = new List(4);
		list.append(4);
		list.append(1);
		list.append(2);
		list.insert(2, 10);
		list.display();
		list.remove(2);
		list.display();
		System.out.println(list.at(2));
		System.out.println("size of the list:"+list.size());
	}

}

未完待续..........

java实现链表

标签:ack   nod   转型   ext   list   bar   两种方法   pac   station   

原文地址:http://blog.51cto.com/13047263/2070815

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!