java 实现单链表
程序员文章站
2024-03-01 09:10:04
...
class MyLinkedList {
class Node {
int val;
Node next;
public Node() {
}
public Node(int val) {
this.val = val;
}
}
Node head = null;
int size = 0;
public MyLinkedList(int x) {
this.head = new Node(x);
this.size = 1;
}
public MyLinkedList() {
this.head = new Node();
this.size = 0;
}
public int get(int index) {
if (index >= size || index < 0)
return -1;
Node tmp = head;
for (int i = 0; i < index; i++) {
tmp = tmp.next;
}
return tmp.val;
}
public void addAtHead(int val) {
Node tmp = new Node(val);
tmp.next = head;
head = tmp;
size++;
}
public void addAtTail(int val) {
if (size==0){
addAtHead(val);
return;
}
Node add = new Node(val);
Node tmp = head;
for (int i = 1; i < size; i++) {
tmp = tmp.next;
}
tmp.next = add;
add.next = null;
size++;
}
public void addAtIndex(int index, int val) {
if (index==0){
addAtHead(val);
return;
}
if (index>size)return;
Node node = new Node(val);
Node tmp = head;
for (int i = 1; i < index; i++) {
tmp = tmp.next;
}
node.next = tmp.next;
tmp.next = node;
size++;
}
public void deleteAtIndex(int index) {
if (index==0){
head=head.next;
size--;
return;
}
if (index>=size)return;
Node tmp = head;
for (int i = 1; i < index; i++) {
tmp = tmp.next;
}
LinkedList
tmp.next = tmp.next.next;
size--;
}
}
下面有单链表环的小用法
https://blog.csdn.net/suibianshen2012/article/details/52032138