Java 手写实现链表功能
个人手写,可能存在不足之处,欢迎各位斧正。
不说废话直接上代码。
public class MyList {
private MyNode head;
public MyList() {
head = new MyNode(null,null);
}
// 清空链表
public void clear(){
head.item = null;
head.next = null;
}
// 获取链表长度
public int getLength(){
int count = 0;
MyNode cur = head;
while (cur.next != null){
cur = cur.next;
count++;
}
return count;
}
// 获取第i个元素
public String get_i(int i){
if(i < 0 || i> this.getLength()){
System.out.println("位置超出边界");
}
MyNode cur = head;
int count = 1;
while (cur.next != null){
cur = cur.next;
if(count == i){
return cur.item;
}
count++;
}
return null;
}
// 在尾部添加一个元素
public void insert(String str){
// 初始化取头结点
MyNode myNode = head;
// 取最后一个节点
while (myNode.next != null){
myNode = myNode.next;
}
// 将新的值插入到链表尾部
myNode.next = new MyNode(str,null);
}
// 在指定位置后添加一个元素
public void insert(int i, String str){
if(i < 0 || i> this.getLength()){
System.out.println("插入位置超出边界");
return;
}
// 保存首节点
MyNode cur = head;
for(int j = 0;j < i;j++){
cur = cur.next;
}
// 保存后继节点
MyNode cur_next = cur.next;
// 指定当前节点的后继节点为新节点,并新节点指向原来的后继节点
cur.next = new MyNode(str,cur_next);
}
// 链表按照位置更改值
public void update(int i,String str){
if(i < 0 || i> this.getLength()){
System.out.println("位置超出边界");
return;
}
MyNode cur = head;
for(int j = 0;j<i;j++){
cur = cur.next;
}
cur.item = str;
}
// 删除指定位置值
public void remove(int i){
if(i < 0 || i> this.getLength()){
System.out.println("位置超出边界");
return;
}
i = i-1;
MyNode cur = head;
for(int j = 0;j < i;j++){
cur = cur.next;
}
cur.next = cur.next.next;
}
public String toString(){
String rst = "";
// 使用cur来保存头结点,否则打印完成后指针就在最后了
MyNode cur = head;
while (cur.next != null){
// 要先取下一个在添加不然就会少一个
cur = cur.next;
rst += cur.item+"\t";
}
return rst;
}
}
// 定义节点类
class MyNode{
public String item;
public MyNode next;
public MyNode(String item, MyNode next) {
this.item = item;
this.next = next;
}
}
简单测试
public static void main(String[] args) {
MyList myList1 = new MyList();
myList1.insert("1");
myList1.insert("2");
myList1.insert("4");
System.out.println(myList1.toString());
myList1.insert(2, "5");
System.out.println(myList1.toString());
myList1.update(2, "6");
System.out.println(myList1.toString());
myList1.remove(4);
System.out.println(myList1.toString());
System.out.println(myList1.getLength());
}
结果为:
1 2 4
1 2 5 4
1 6 5 4
1 6 5
3