Linked List - Insert, Remove
程序员文章站
2022-04-18 20:09:22
...
Main.java
public class Main {
public static void main(String[] args) {
LinkedList206<String> lnl = new LinkedList206<>();
lnl.add("Kaipo");
lnl.add("Han");
lnl.add("Rex");
lnl.add("Lana");
lnl.add("Tiana");
lnl.printAll();
lnl.insertAt(0, "Mike");
//String deleted = lnl.removeAt(0);
System.out.println("Just added Mike to the list");
lnl.printAll();
//System.out.println(lnl.get(2));
LinkedList206<Double> nums = new LinkedList206<>();
nums.add(Math.PI);
nums.add(Math.E);
nums.add(4.0);
nums.printAll();
}
}
LinkedList206.java
public class LinkedList206<E> {
Node206<E> head;
public LinkedList206() {
head = null;
}
public void add(E k) {
Node206<E> n = new Node206<E>(k);
if (head == null) {
head = n;
} else {
//add the new node to the
//end of the list.
Node206<E> tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = n;
}
}
public void printAll() {
Node206<E> tmp = head;
while (tmp != null) {
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public E get(int index) {
Node206<E> tmp = head;
for (int i=0; i<index; i++) {
tmp = tmp.next;
}
return tmp.data;
}
public E removeAt(int index) {
E result;
Node206<E> tmp = head;
if (index == 0) {
result = head.data;
head = head.next;
} else {
for (int i=0; i<index-1; i++) {
tmp = tmp.next;
}
result = tmp.next.data;
tmp.next = tmp.next.next;
}
return result;
}
public void insertAt(int index, E newData) {
Node206<E> n = new Node206<E>(newData);
Node206<E> tmp = head;
if (index == 0) {
n.next = head;
head = n;
} else {
for (int i=0; i<index-1; i++) {
tmp = tmp.next;
}
//make the new node point to the rest of the list
n.next = tmp.next;
//make the node before it, point to the new node
tmp.next = n;
}
}
}
Node206.java
public class Node206<E> {
E data;
Node206<E> next;
public Node206(E k) {
data = k;
next = null;
}
}
上一篇: Mac切换Python版本
推荐阅读
-
Java基础学习总结(129)——Arrays.asList得到的List进行add和remove等操作出现异常解析
-
时间复杂度————被list.insert坑了
-
Python操作列表之List.insert()方法的使用
-
Java list.remove( )方法需要注意的地方
-
Python 删除List元素的三种方法remove、pop、del
-
【LeetCode OJ 328】Odd Even Linked List
-
【转载】C#中使用List集合的Insert方法在指定位置插入数据
-
数据结构与算法 —— 链表linked list(04)
-
PTA 02-线性结构3 Reversing Linked List (25 分)
-
PAT-A-1052 Linked List Sorting