public class Node {
public Node next;//指针域
public Object data;//数据域
public Node(Object data){
this.data = data;
this.next = null;
}
}
package com.test;
public class LinkList {
private Node head;//头指针
//表尾插入节点
public void addTail(Object data){
Node s = new Node(data);//创建一个新节点
Node p = head;
if(p==null){
s.next = head;
head = s;
}else {
while(p.next!=null){
p = p.next;
}
s.next = p.next;
p.next = s;
}
}
//表头插入节点
public void addHead(Object data){
Node s = new Node(data);//创建一个新节点
s.next = head;
head = s;
}
//根据位置插入节点
public void insertByPoint(Object data ,int i){
Node s = new Node(data);
Node p = head;
int j=0;
if(p==null){
s.next = head;
head = s;
}else {
while((p.next!=null)&&(j<i-1)){
p = p.next;
j++;
}
if((p==null)||j>i-1){
System.out.println("位置出错");
return;
}
s.next = p.next;
p.next = s;
}
}
//删除指定位置的节点
public void delete(int i){
Node p = head;
int j = 0;
if(p==null){
System.out.println("链表为空!");
return;
}else {
while((p.next!=null)&&(j<i-1)){
p = p.next;
j++;
}
if((p.next==null)||j>i-1){
System.out.println("删除位置超界");
return;
}
Node q = p.next;
Object a = q.data;//删除的节点的值
p.next = p.next.next;
}
}
//打印链表
public void printAll(){
Node p = head;
while(p!=null){
System.out.print(p.data+"->");
p = p.next;
}
System.out.println();
}
public static void main(String[] args) {
LinkList ll = new LinkList();
ll.addTail(1);
ll.addTail(2);
ll.addTail(3);
ll.addTail(4);
ll.addTail(5);
ll.printAll();
ll.insertByPoint(6,2);
ll.printAll();
}
}