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

【算法数据结构Java实现】Java实现单链表

时间:2014-12-02 17:19:08      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   sp   

1.背景

          单链表是最基本的数据结构,仔细看了很久终于搞明白了,差不每个部分,每个链都是node的一个对象。需要两个参数定位:一个是index,表示对象的方位。另一个是node的对象。

bubuko.com,布布扣


2.代码


node类
public class Node {
	 protected Node next;
	 protected int data;
	 public Node(int data){
		 this.data=data;
	 }
	 public void display(){
     System.out.print(data+"");
   }
}

arraylist类
public class myArrayList {
      public Node first;//定义头结点
      private int pos=0;//节点位置
      public myArrayList(){
    	  // this.first=null;
      }
      //插入一个头结点
      public void addFirstNode(int data){
    	    Node node=new Node(data);
    	    node.next=first;
    	    first=node;
      }
      //删除头结点
      public Node deleteFirstNode(){
    	    Node tempNode=first;
    	    first=tempNode.next;
    	    return tempNode;
      }
      // 在任意位置插入节点 在index的后面插入  
      public void add(int index, int data) {  
           Node node = new Node(data);  
           Node current = first;  
           Node previous = first;  
            while ( pos != index) {  
               previous = current;  
               current = current. next;  
                pos++;  
           }  
           node. next = current;  
           previous. next = node;  
            pos = 0;  
      }  
      // 删除任意位置的节点  
      public Node deleteByPos( int index) {  
           Node current = first;  
           Node previous = first;  
            while ( pos != index) {  
                pos++;  
               previous = current;  
               current = current. next;  
           }  
            if(current == first) {  
                first = first. next;  
           } else {  
                pos = 0;  
               previous. next = current. next;  
           }  
            return current;  
      }     
      public void displayAllNodes() {  
          Node current = first;  
           while (current != null) {  
              current.display();
              System.out.println();
              current = current. next;  
          }            
     }  
      
}


实现的main函数:
public class Main {
   public static void main(String args[]){
	   myArrayList ls=new myArrayList();   	  
	   ls.addFirstNode(15);	   
	   ls.addFirstNode(16);
	   ls.add(1, 144);
	   ls.add(2, 44);
	   ls.deleteByPos(1);
	  ls.displayAllNodes();	   
   }
}



实现结果:

16

44

15




/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/


【算法数据结构Java实现】Java实现单链表

标签:des   style   blog   http   io   ar   color   os   sp   

原文地址:http://blog.csdn.net/buptgshengod/article/details/41681017

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