import java.util.Stack;
public class SingleLinkedList {
static class Node{
public int value;
Node next;
public Node(int value) {
this.value = value;
}
}
public Node head;
public int size(){
int count=0;
Node current =head;
while(current!=null){
current=current.next;
count++;
}
return count;
}
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){
addFirst(data);
}
else{
Node current=head;
while(current.next!=null){
current=current.next;
}
current.next=node;
}
}
public void addIndex(int index,int data){
if(index==0){
addFirst(data);
return;
}
if(index==size()){
addLast(data);
return;
}
check(index);
Node previousNode=FindPreviousNode(index);
Node node=new Node(data);
node.next=previousNode.next;
previousNode.next=node;
}
private void check(int index){
if(index<0||index>size())
throw new ArrayIndexOutOfBoundsException("index位置不合法");
}
private Node FindPreviousNode(int index){
Node current =head;
for(int i=0;i<index-1;i++){
current=current.next;
}
return current;
}
public boolean contains(int key){
Node current =head;
while(current!=null){
if(current.value==key) {
return true;
}
current=current.next;
}
return false;
}
public void remove(int key){
if(head.value==key){
head=head.next;
return;//r如果删除的是首元素
}
//如果删除的是中间元素
Node current=head;
while(current.next!=null){
if(current.next.value==key){
current.next=current.next.next;
break;//不退出会报空指针异常
}
current=current.next;
}
}
public void removeAllKey(int key){
if(head==null){
return;
}
Node previousNode=head;
Node current=head.next;
while(current!=null){
if(current.value==key){
previousNode.next=current.next;
}else{
previousNode=current;
}
current=current.next;
}
if(head.value==key){
head=head.next;
}
}
public void clear(){
Node current=head;
while(current!=null){
Node nextNode=current.next;
current.next=null;
current=nextNode;
}
head=null;
}
public void display(){
Node current=head;
while(current!=null){
System.out.print(current.value+" ");
current=current.next;
}
System.out.println();
}
public static void display(Node head){
Node current=head;
while(current!=null){
System.out.print(current.value+" ");
current=current.next;
}
System.out.println();
}
public void printList(){
//倒序遍历递归方法
if(head==null){
return ;
}
Node current=head;
if(current.next!=null){
printList(current.next);
}
System.out.println(current.value);
}
public void printList (Node head) {
//倒序遍历将链表压入栈中依次弹出
if (head == null) {
System.out.println("");
return;
}
Node current=head;
Stack<Node> stack=new Stack<>();
while(current!=null){
stack.push(current);
current=current.next;
}
while(!stack.isEmpty()){
System.out.print(stack.pop().value+" ");
}
}
}
数据结构单链表的模拟实现
最新推荐文章于 2025-01-03 09:32:18 发布