现在的位置: 首页 > 综合 > 正文

Java 链表结构

2014年11月06日 ⁄ 综合 ⁄ 共 1764字 ⁄ 字号 评论关闭

public class LinkList {
 
 private LNode firstNode = new LNode();
 
 //Insert the elem after the first node
 public void insertElem(String name) {
  
  LNode temp = null;

  if(firstNode != null && firstNode.next == null) {
   //if the lnode has a elem
   LNode node = new LNode();
   node.data = name;
   firstNode.next = node;
  } else {
   //if the lnode has more than a elem
   temp = firstNode.next;
   LNode node = new LNode();
   node.data = name;
   firstNode.next = node;
   firstNode.next.next = temp;
  }
  
 }
 
 public void insertElem(String name, int index) {
  
  LNode temp = firstNode;
  int i = 1;
  while(temp != null && i < index) {
   temp = temp.next;
   ++i;
  }
  
  LNode node = new LNode();
  node.data = name;
  node.next = temp.next;
  temp.next = node;
  
 }
 
 public LNode getElem(int index) {
  
  LNode temp = firstNode;
  
  int i = 1;
  while(temp != null && i < index + 1) {
   temp = temp.next;
   ++i;
  }
  
  return temp;
  
 }
 
 public void removeElem(int index) {
  
  LNode temp = firstNode;
  
  int i = 1;
  while(temp != null && i < index) {
   temp = temp.next;
   ++i;
  }
  
  temp.next = temp.next.next;
  
 }
 
 public void printAll() {
  LNode temp = firstNode;
  int i = 0;
  while(temp != null && temp.next != null) {
   if( i > 0)
    System.out.println(i + " : " + temp.data);
   temp = temp.next;
   ++i;
  }
 }
 
 //Test
 public static void main(String[] args) {
  LinkList linkList = new LinkList();
  linkList.insertElem("c");
  linkList.insertElem("b");
  linkList.insertElem("a");
  linkList.insertElem("d", 1);
  linkList.insertElem("e", 3);
  //before removed
  System.out.println("Before remove:");
  linkList.printAll();
  
  linkList.removeElem(2); 
  System.err.println("Remove 2 success!");
  //after removed
  System.out.println("After remove:");
  linkList.printAll();
 }
 
}

//Just like the C language's struct
class LNode {
 
 public Object data;
 
 public LNode next;
 
 //use to initial the first node ,and do the malloc for the other node
 public LNode() {
  super();
  this.data = "";
  this.next = null;
 }

}

抱歉!评论已关闭.