手写单链表,直接上代码
public class SingleLinkedList {
public static class Node {
int value;
Node next;
public Node(int value){
this.value = value;
}
}
public Node head;
//头插法
public void addFirst(int data){
Node node = new Node(data);
node.next = head;
head = node;
}
//尾插法
public void addLast(int data) {
Node node = new Node(data);
if(head==null){
head = node;
return;
}
//后面开始处理尾节点
Node current = head;
while(current.next!=null){
current = current.next;
}
//此时已经走到了最后一个节点,把最后一个节点与新节点简历引用关联
current.next = node;
}
//任意位置插入,第一个数据节点为0号下标
public void addIndex(int index, int data){
//校验index合法性
checkRange(index);
//下标为0直接头插
if (index==0){
addFirst(data);
return;
}
//下标为size 直接尾插
if (index ==size()){
addLast(data);
return;
}
Node prevNode = findPrevNodeByIndex(index);
Node node = new Node(data);
// for (int i = 0; i < index-1; i++) {
// current = current.next;
// }
node.next = prevNode.next;
prevNode.next = node;
}
private Node findPrevNodeByIndex(int index) {
// 定义一个临时变量,用来遍历
Node current = head;
for (int i = 0; i < (index - 1); i++) {
current = current.next;
}
return current;
}
private void checkRange(int index) {
if (index<0||index>size()){
throw new IndexOutOfBoundsException("下标不合法,index = "+ index);
}
}
//查找是否包含关键字key是否在单链表当中
public boolean contains(int key){
Node current = head;
while(current.next!=null){
if (current.value==key){
return true;
}
current = current.next;
}
return false;
}
//得到单链表的长度
public int size(){
Node node = head;
int count = 0;
while (node!=null){
count++;
node = node.next;
}
return count;
}
//删除第一次出现关键字为key的节点
public void remove(int key) {
//如果头节点就是要找的节点
if (head.value == key) {
head = head.next;
}
// 如果代码已经走到这里了
Node current = head;
while (current.next != null) {
if (current.next.value == key) {
current.next = current.next.next;
return;
}
current= current.next;
}
}
//删除所有值为key的节点
public void removeAllKey(int key){
//首先判断是不是空链表
if (head==null){
return;
}
//定义两个临时变量,一个用头节点,另一个用头节点的下一个节点
Node prev = head;
Node current = prev.next;
while(current!=null){
if (current.value==key){
prev.next = current.next;
}
else{
prev = current;
current = prev.next;
}
current = current.next;
}
// 最后处理一下头节点
if (head.value == key) {
head = head.next;
}
}
//清空列表
public void clear(){
head = null;
}
//打印链表
public void display(){
Node current = head;
StringBuilder sb = new StringBuilder();
sb.append("[");
while(current!=null){
sb.append(current.value);
if (current.next!=null){
sb.append(", ");
}
current = current.next;
}
sb.append("]");
System.out.println(sb.toString());
}
}
本文介绍了一个简单的单链表实现,包括节点的插入、删除、查找等基本操作,并提供了完整的Java代码示例。
1569

被折叠的 条评论
为什么被折叠?



