testlinkedlist.java

来自「JAVA培训用实用代码」· Java 代码 · 共 77 行

JAVA
77
字号
public class TestLinkedList{
	public static void main(String args[]){
		TestLinkedList e = new TestLinkedList();
		Node myList = e.create();
		e.show(myList);
		Node result = e.delete(myList,22);
		e.show(result);
	}
		
	public Node create(){
		Node n1 = new Node(11);
		Node n2 = new Node(22);
		Node n3 = new Node(33);
		Node n4 = new Node(44);
		Node n5 = new Node(55);
		n1.setNext(n2);
		n2.setNext(n3);
		n3.setNext(n4);
		n4.setNext(n5);	
		return n1;					
	}
	
	public void show(Node n){
		while(n!=null){
			System.out.print(n.getData() + "   ");
			n = n.getNext();	
		}
		System.out.println();				
	}
	
	public Node delete(Node start,int value){
		while(start!=null && start.getData()==value){
			start = start.getNext();	
		}
		Node n = start;
		while(n!=null && n.getNext()!=null){
			Node follow = n.getNext();
			if(follow.getData() == value){
				n.setNext(follow.getNext());	
			}
			n = follow;	
		}
		return start;				
	}		
}


class Node{
	private int data; 	//节点中保存的数据
	private Node next;	//节点中的指针属性,指向下一个Node对象
	
	public Node(int data){
		this.data = data;
		next = null;	
	}
	
	public Node(int data,Node next){
		this.data = data;
		this.next = next;	
	}
	
	public void setData(int data){
		this.data = data;	
	}
	
	public int getData(){
		return data;	
	}
	
	public void setNext(Node next){
		this.next = next;				
	}
	
	public Node getNext(){
		return next;	
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?