java实现单向链表的增删改查
package com.eshore.ac.batch;
import com.eshore.ac.util.DESUtil;
import com.eshore.ac.util.ObjectUtil;
import org.junit.Test;
import java.util.*;
public class demoTest {
private class Node {
private Object obj;
private Node next = null;
Node(Object obj){
this.obj = obj;
}
}
private Node head = null;
public void add(Object obj) {
Node node=new Node(obj);
node.next=head;
head=node;
}
public Object deletehead() throws Exception{
if(head==null){
throw new Exception("this link is Empty");
}
Node temp=head;
head=head.next;
return temp.obj;
}
public void display() throws Exception{
if(head==null){
throw new Exception("this link is Empty");
}
Node cur=head;
while(cur!=null){
System.out.print(cur.obj+"--->");
cur=cur.next;
}
System.out.print("\n");
}
public boolean isEmpty() {
return (head==null);
}
public boolean contains(Object obj) throws Exception{
if (head==null){
throw new Exception("this link is Empty");
}
Node cur=head;
while(cur!=null){
if(cur.obj.equals(obj)){
return true;
}
cur=cur.next;
}
return false;
}
public void remove(Object obj) throws Exception{
if (head==null){
throw new Exception("this link is Empty");
}
if(head.obj.equals(obj)){
head=head.next;
remove(obj);
}else {
Node pre=head;
Node cur=head.next;
while(cur!=null){
if(cur.obj.equals(obj)){
pre.next=cur.next;
}
pre=cur;
cur=cur.next;
}
}
}
public void removeDuplicate(Node head) throws Exception{
if (head==null){
throw new Exception("this link is Empty");
}
demoTest newListNode=new demoTest();
Node pre=head;
Node cur=head.next;
newListNode.add(pre.obj);
while(cur!=null){
if(!newListNode.contains(cur.obj)){
newListNode.add(cur.obj);
pre=cur;
cur=cur.next;
}else {
pre.next=cur.next;
cur=cur.next;
}
}
}
@Test
public void test() throws Exception {
demoTest listNode = new demoTest();
listNode.add(1);
listNode.add(1);
listNode.add(2);
listNode.add(3);
listNode.add(2);
listNode.add(3);
listNode.add(3);
listNode.display();
listNode.removeDuplicate(listNode.head);
listNode.display();
}
}