Java 简单链表实现
1.初衷
最近在看Java基础,有一章节涉及到链表,便记之所学所得。
2.链表的定义
链表是存储地址不连续的线性存储结构
3.链表的基本结构
一个节点包含当前节点,与下个节点的引用
4.简单链表的实现
定义一个节点Node
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * @author qiuling */ public class Node { /**当前节点数据*/ private int data; /**下个节点引用*/ private Node next; public Node(int data) { this.data = data; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }
4.1增加节点
/** * 增加节点 * @param data 节点数据 */ public void addNode(int data){ Node node = new Node(data); if (null == head){ head = node; }else { Node cur = head; //找到链表末尾位置添加数据 while(null != cur.getNext()){ cur = cur.getNext(); } cur.setNext(node); } }
4.2遍历打印节点
/** * 遍历元素 */ public void print(){ Node cur = head; //这个地方注意下不能判断temp.getNext, //the last Node 的next是null while (null != cur){ System.out.println(cur.getData()); cur = cur.getNext(); } }
addNode and print test :
4.3插入节点到指定位置
/** * 插入节点至指定位置 * @param index 链表位置 * @param node 节点 */ public void insertNodeByIndex(int index,Node node){ //判断插入位置 if (index<1 || index>size()){ return; } Node cur = head; int length =1; while (null != cur){ //找到指定位置 if (index == length++){ //插入节点的next = 当前节点的next node.setNext(cur.getNext()); //当前节点的next = 插入的node cur.setNext(node); return; } cur = cur.getNext(); } }
test :
4.4删除指定位置节点
与上面插入指定位置节点相似
/** * 删除指定位置的节点 * @param index 链表位置 */ public void delNodeByIndex(int index){ //判断删除节点位置是否合法 if (index<1 || index>size()){ return; } Node cur = head; int i = 1; while (cur != null) { if (index == i++) { //当前node的next改为删除节点的next cur.setNext(cur.getNext().getNext()); return; } cur = cur.getNext(); } }
test :
4.5获取链表长度
/** * 获取链表长度 * @return */ public int size(){ Node cur = head; int size = 0; while (null != cur){ size++; cur = cur.getNext(); } return size; }
4.6判断链表是否包含某元素
/** * 判断链表是否包含数据 * @param data * @return */ public boolean isContain(int data){ Node cur = head; while (null != cur){ if (cur.getData() == data){ return true; } cur = cur.getNext(); } return false; }
4.7链表的反转
/** * 反转链表 */ public void reserveLink(){ //头节点 Node cur = head; //前一个节点 Node pre = null; while (null != cur){ //暂存当前节点的下个节点 Node next = cur.getNext(); //指针反转 cur.setNext(pre); //前一个节点和当前节点顺序推移 pre = cur; cur = next; } head = pre; }
5.完结
这些东西并不是很多,自己却是拖了蛮久的,要坚持努力下去,不要丧失前进的勇气。