设计一个Java程序,来实现单向链表添加节点的过程,并且允许可以在链表头部、链表末尾和链表中间三种不同位置插入新节点。
package LinkList;
public class Node1 {
int data;
Node1 next;
public Node1(int data) {
this.data=data;
this.next=null;
}
}
package LinkList;
public class insert {
public Node1 first;
public Node1 last;
public boolean isEmpty(){
return first==null;
}
public void print() {
Node1 current=first;
while(current!=null) {
System.out.print("["+current.data+"]");
current=current.next;
}
System.out.println();
}
public insert Concatenate(insert head1,insert head2) {
insert ptr;
ptr=head1;
while(ptr.last.next!=null) ptr.last=ptr.last.next;
ptr.last.next=head2.first;
return head1;
}
public void insert(Node1 ptr) {
Node1 temp;
Node1 newNode;
if(this.isEmpty()) {
first=ptr;
last=ptr;
}else {
if(ptr.next==first) {
ptr.next=first;
first=ptr;
}else {
if(ptr.next==null) {
last.next=ptr;
last=ptr;
}else {
temp=first;
newNode=first;
while(ptr.next!=newNode.next) {
temp=newNode;
newNode=newNode.next;
}
temp.next=ptr;
ptr.next=newNode;
}
}
}
}
}
package LinkList;
public class InsertTest {
public static void main(String args[]) {
insert list1=new insert();
insert list2=new insert();
Node1 node1=new Node1(5);
Node1 node2=new Node1(6);
list1.insert(node1);
list2.insert(node2);
Node1 node3=new Node1(7);
Node1 node4=new Node1(8);
list2.insert(node3);
list2.insert(node4);
list1.Concatenate(list1, list2);
list1.print();
}
}