码迷,mamicode.com
首页 > 其他好文 > 详细

单链表的简单实现

时间:2017-08-17 18:33:53      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:his   ack   插入   i++   nod   insert   this   auto   auth   

//定义一个节点类 
class Node{
    int data;
    Node nextNode;
    
    public Node(int data) {
        // TODO Auto-generated constructor stub
        this.data = data;
    }
}

链表类:

package test;

/**
 * 
 * @author dao
 *
 */
// 链表类
public class ListNode {
    Node firstNode; // 第一个节点
    int length = 0;
    Node current; // 当前节点
    Node previous; // 指定位置插入的未插入时current的下一节点

    // 增加node
    public void addNode(int data) {
        if (length == 0) { // 链表为空时,增加的为首节点
            Node node = new Node(data);
            node.nextNode = node;
            firstNode = node;
            current = firstNode;
            length++;
        } else {
            Node node = new Node(data); // 不为空的链表增加节点
            current.nextNode = node;
            current = node;
            length++;
        }
    }

    // 任意位置增加node
    public void insertNode(int i, int data) {
        int pos = 1;
        Node node = new Node(data);
        current = firstNode;
        if (i == 1) { // 插入位置为1时,首节点更换
            firstNode = node;
            node.nextNode = current;
            current = firstNode;
        } else if (i > length) { // 判断链表是否有插入位置
            System.out.println("不能在该位置插入");
            return;
        } else {
            while (i - 1 != pos) {
                current = current.nextNode;
                pos++;
            }
        }
        Node nodeNext = current.nextNode; // 未插入时current的下一节点,因为要在两个节点间插入要临时保存这两个节点的。
        current.nextNode = node; // 下个节点的引用更换
        node.nextNode = nodeNext;
        length++;
    }

    // 取出所有node
    public void printAllNode() {
        current = firstNode;
        for (int i = 1; i <= length; i++) { // 从第一个节点开始,依次打印出所有节点
            System.out.println(current.data);
            current = current.nextNode;
        }
    }

}

// 定义一个节点类
class Node {
    int data;
    Node nextNode;

    public Node(int data) {
        // TODO Auto-generated constructor stub
        this.data = data;
    }
}

 

单链表的简单实现

标签:his   ack   插入   i++   nod   insert   this   auto   auth   

原文地址:http://www.cnblogs.com/halo-yang/p/7383114.html

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