Java实现单链表
Posted DeepSleeping丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现单链表相关的知识,希望对你有一定的参考价值。
package list;
/**
* 节点
*
* @author DeepSleeping
*
*/
public class ListNode {
Object data;
ListNode next;
public ListNode(Object data) {
super();
this.data = data;
}
}
package list;
/**
* 单链表
*
* @author DeepSleeping
*
*/
public class SingleList implements MyList {
private ListNode first;
private ListNode last;
private int size;
@Override
public void add(Object element) {
if (first == null) {
first = new ListNode(element);
last = first;
}else{
last.next = new ListNode(element);
last = last.next;
}
size++;
}
@Override
public void delete(Object element) {
ListNode p = first;
ListNode pre = null;
while(p != null){
if (p.data.equals(element)) {
//如果删除的是第一个元素
if (p == first) {
first = first.next;
}else{
pre.next = p.next;
}
break; //注意,删除了第一个相同的元素之后应该跳出循环
}
pre = p;
p = p.next;
}
size--;
}
@Override
public void delete(int index) {
if (index < 0 || index >= size) {
return;
}
int i = 0;//指针指向的节点的索引
ListNode p = first;
ListNode pre = null;
while(p != null){
if (i == index) {
if (p == first) {
first = first.next;
}
else{
pre.next = p.next;
}
break;
}
pre = p;
p = p.next;
i++;
}
size--;
}
@Override
public void update(int index, Object newElement) {
int i = 0;//指针指向的节点的索引
ListNode p = first;
while(p != null){
if (i == index) {
p.data = newElement;
}
p = p.next;
i++;
}
}
@Override
public boolean contains(Object target) {
ListNode p = first;
while(p != null){
if (p.data.equals(target)) {
return true;
}
p = p.next;
}
return false;
}
@Override
public Object at(int index) {
if (index < 0 || index >= size) {
return null;
}
int i = 0;//指针指向的节点的索引
ListNode p = first;
while(p != null){
if (i == index) {
return p.data;
}
p = p.next;
i++;
}
return null;
}
@Override
public int indexOf(Object element) {
int i = 0;
ListNode p = first;
while(p != null){
if (p.data.equals(element)) {
return i;
}
p = p.next;
i++;
}
return -1;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
ListNode p = first;
while(p != null){
sb.append(p.data);
if (p.next != null) {
sb.append(",");
}
p = p.next;
}
sb.append("]");
return sb.toString();
}
}
以上是关于Java实现单链表的主要内容,如果未能解决你的问题,请参考以下文章