日期:2014-05-20  浏览次数:20616 次

java中链表的操作
本人初学java有个问题想问一下,希望各位大虾帮下忙,先谢谢了!
      在java中不是没有了指针吗,那么java中是如何对链表进行操作的呢??
请附上例子讲一下,再次谢谢!

------解决方案--------------------
public class LinkedList {
private Node header;

/**
* @return the header
*/
public Node getHeader() {
return header;
}

/**
* @param header the header to set
*/
public void setHeader(Node header) {
this.header = header;
}

public void printListContext(){
if (this.header == null){
System.out.println( "Null ");
return;
}
Node temp = this.header;
while(temp != null){
System.out.print(temp.getContext() + "--> ");
temp = temp.getNext();
}
System.out.print( "null ");
System.out.println();
}

public void resverce(){
if (this.header == null || this.header.getNext() == null){
return;
}

Node current = this.header,tempNext = this.header.getNext();
int cnt = 0;
while(tempNext != null){
cnt ++;
Node temp = current;
current = tempNext;
tempNext = tempNext.getNext();
if (cnt == 1){
temp.setNext(null);
}
current.setNext(temp);
}
this.header = current;
}

public void buildLinkedList(){
Node n4 = new Node( "4 ",null);
Node n3 = new Node( "3 ",n4);
Node n2 = new Node( "2 ",n3);
Node n1 = new Node( "1 ",n2);
Node n0 = new Node( "0 ",n1);

this.header = n0;
}

/**
* @param args
*/
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.buildLinkedList();

ll.printListContext();
ll.resverce();
ll.printListContext();

}

class Node {
private String context;
private Node next;
public Node(String context,Node n){
this.context = context;
this.next = n;
}
/**
* @return the context
*/
public String getContext() {
return context;
}
/**
* @return the next
*/
public Node getNext() {
return next;
}
/**
* @param next the next to set
*/
public void setNext(Node next) {
this.next = next;
}
}
}

上面是我自己写的链表~其实java自带有LinkedList~
------解决方案--------------------
没有指针有reference
------解决方案--------------------
如二楼所述,LinkedList可以制作队列和栈.
楼主你不研究代码怎么可能明白啊.把代码拿回去自己好好查阅JDK就能明白.