初识单链表
class Node {
public int data ;
public Node next ;
public Node ( int data ) {
this . data = data;
this . next = null ;
}
}
public class MyLinkedList {
public Node head;
public void addFirst ( int data) {
Node node = new Node ( data) ;
if ( this . head == null ) {
this . head = node;
return ;
}
node. next = this . head;
this . head = node;
}
public void addLast ( int data) {
Node node = new Node ( data) ;
if ( head == null ) {
this . head = node;
return ;
}
Node cur = this . head;
while ( cur. next != null ) {
cur = cur. next;
}
cur. next = node;
}
public void display ( ) {
Node cur = this . head;
while ( cur != null ) {
System . out. print ( cur. data + " " ) ;
cur = cur. next;
}
}
public boolean contains ( int key) {
Node cur = this . head;
while ( cur != null ) {
if ( cur. data == key) {
return true ;
}
cur = cur. next;
}
return false ;
}
public int size ( ) {
Node cur = this . head;
int count = 0 ;
while ( cur != null ) {
count++ ;
cur = cur. next;
}
return count;
}
public void addIndex ( int index, int data) {
Node node = new Node ( data) ;
if ( index == 0 ) {
addFirst ( data) ;
return ;
}
if ( index == this . size ( ) ) {
addLast ( data) ;
return ;
}
searchIndex ( index) ;
Node cur = searchIndex ( index) ;
node. next = cur. next;
cur. next = node;
return ;
}
private Node searchIndex ( int index) {
if ( index < 0 || index > this . size ( ) ) {
throw new RuntimeException ( "index 位置不合法!" ) ;
}
Node cur = this . head;
while ( index - 1 != 0 ) {
cur = cur. next;
index-- ;
}
return cur;
}
private Node searchPrev ( int key) {
Node prev = this . head;
while ( prev. next != null ) {
if ( prev. next. data == key) {
return prev;
} else {
prev = prev. next;
}
}
return null ;
}
public void remove ( int key) {
if ( this . head == null ) {
return ;
}
if ( this . head. data == key) {
this . head = this . head. next;
return ;
}
Node prev = searchPrev ( key) ;
if ( prev == null ) {
System . out. println ( "没有要删除的节点" ) ;
return ;
}
Node del = searchPrev ( key) . next;
prev. next = del. next;
}