单向非循环链表(不带傀儡节点)的方法实现
class Node {
public int data
;
public Node next
;
public Node(int data
) {
this.data
= data
;
}
}
public class SingleList {
public Node head
;
public void addFirst(int data
){
Node node
= new Node(data
);
if(this.head
== null
){
this.head
= node
;
} else {
node
.next
= this.head
;
this.head
= node
;
}
}
public void addLast(int data
){
Node node
= new Node(data
);
if(this.head
== null
){
this.head
= node
;
} else {
Node cur
= this.head
;
while(cur
.next
!= null
){
cur
= cur
.next
;
}
if(cur
.next
== null
){
cur
.next
= node
;
}
}
}
public void addIndex(int index
,int data
) {
Node cur
= this.head
;
Node node
= new Node(data
);
int count
= 0;
if(index
> size() || index
< 0){
System
.out
.println("插入位置不合法");
return;
}
if(index
== 0){
addFirst(data
);
return;
} else {
while(count
< index
- 1){
cur
= cur
.next
;
count
++;
}
node
.next
= cur
.next
;
cur
.next
= node
;
}
}
public boolean contains(int key
) {
Node cur
= this.head
;
while(cur
!= null
){
if(cur
.data
== key
){
return true;
}
cur
= cur
.next
;
}
return false;
}
public void remove(int key
){
if(contains(key
)){
Node cur
= this.head
;
if(this.head
.data
== key
){
this.head
= cur
.next
;
return;
}
while(cur
!= null
){
if(cur
.next
.data
== key
){
cur
.next
= cur
.next
.next
;
return;
}
cur
= cur
.next
;
}
} else {
System
.out
.println("该链表内没有key值 删除错误");
return;
}
}
public void removeAllKey(int key
) {
boolean flg
= true;
while(contains(key
)){
remove(key
);
flg
= false;
}
if(flg
){
System
.out
.println("该链表内没有key值 删除错误");
}
}
public int size() {
Node cur
= this.head
;
int count
= 0;
while(cur
!= null
){
count
++;
cur
= cur
.next
;
}
return count
;
}
public void display() {
if(this.head
== null
){
System
.out
.print("此时链表为空");
}
Node cur
= this.head
;
while(cur
!= null
){
System
.out
.print(cur
.data
+ " ");
cur
= cur
.next
;
}
System
.out
.println();
}
public void clear() {
}
public static void main
(String
[] args
){
SingleList singleList
= new SingleList();
singleList
.addLast(8);
singleList
.addLast(8);
singleList
.addLast(8);
singleList
.addLast(8);
singleList
.addIndex(4,0);
singleList
.addIndex(2,10);
singleList
.addIndex(0,9);
singleList
.display();
singleList
.removeAllKey(8);
singleList
.display();
}
}
转载请注明原文地址: https://lol.8miu.com/read-7179.html