java中的指针
public class Test {
public static void main(String [] args){
A a=new A();//a是一个对象
A b=a;A c=a;//b 和 c都是指向同一个对象a的指针
b.a=20;//b是指针 这里其实修改了a.a
System.out.println(c.a);//c也是指向a的指针 //所以输出20
}
}
class A{
int a=10;
}
利用指针写一个简单的的单向链表
class ListNode<E> {
private E item;//存放泛型变量
public ListNode<E> next;//这是指针
public ListNode(E thatItem) {
this.item = thatItem;
next = null;//初始指针指向null
}
public void setNext(E target) {
next = new ListNode(target);//把指针指向一个构造出来的对象
}
public E getItem() {
return this.item;
}
public void setItem(E thatItem) {
this.item = thatItem;
}
}
一个简单的双向链表
public class DoubleListNode<E> {
private ListNode front;
public DoubleListNode(E item) {//constructor
front=new ListNode(item);
}
public void addTop(E target){//类似链表栈的push
front =front.ListNodeNext(target,front) ;
}
public void addBack(E target){//类似链表栈的add
ListNode node=front;
for(;node.getNext()!=null;node=node.getNext()){
}
node.setNext(new ListNode(target));
}
}
class Main{
public static void main(String[] args){
DoubleListNode ls=new DoubleListNode("a");
ls.addBack("b");
ls.addTop("c");
}
}
public class ListNode<E> {//双向节点
private E item; //节点的item
private ListNode<E> next; //左指针
private ListNode<E> pre;//右指针
public ListNode(E item) { //constructor
this.item = item;
next = null;
pre = null;
}
public ListNode ListNodeNext(E item,ListNode thatNext){//类似链表栈的push
ListNode node =new ListNode(item);
node.setNext(this);
this.pre=node;
return node;
}
public ListNode ListNodePre(E item,ListNode thatNext){//类似链表栈的push
ListNode node =new ListNode(item);
node.setPre(this);
this.next=node;
return node;
}
public E getItem() {
return item;
}
public ListNode<E> getNext() {
return next;
}
public void setItem(E item) {
this.item = item;
}
public void setNext(ListNode<E> thatNext) {//使用tahtNext 设置两条链接
this.next = thatNext;
thatNext.pre=this;
}
public ListNode<E> getPre() {
return pre;
}
public void setPre(ListNode thatPre) {
this.pre = thatPre;
thatPre.next=this; //设置两条链接
}
}