62,614
社区成员
发帖
与我相关
我的任务
分享
public class LinkNode {
public String data;
public LinkNode next;
LinkNode(){
this.data = "a";
this.next = null;
}
LinkNode(String string){
this.data = string;
this.next = null;
}
}
public class LinkList {
public LinkNode head = null;//头指针
private LinkNode currentNode = null;//遍历用节点
LinkList(){}
LinkList(int n){
for(int i = 0; i<n; i++){
add();
}
}
public int getLength(){
if(head == null){
return 0;
}
else{
currentNode = head;
int count = 0;
while(currentNode != null){
currentNode = currentNode.next;
count++;
}
return count;
}
}
//头插法批量添加节点
public void add(){
LinkNode tempNode = new LinkNode();
tempNode.next = head;
head= tempNode;
}
//在第i个节点之后插入新节点
public void insert(int i,String string){
if(getLength() >= i){
LinkNode tempNode = new LinkNode(string);
if(i == 0){ //头指针后插入节点
tempNode.next = head;
head = tempNode;
}
else{
currentNode = head;
if(i == 1){ //第一个节点后插入
tempNode.next = currentNode.next;
currentNode.next = tempNode;
}
else{ //一般位置插入
for(int j =0; j < (i-1); j++){
currentNode = currentNode.next;
}
tempNode.next = currentNode.next;
currentNode.next = tempNode;
}
}
}
else{
System.out.println("要插入的位置不存在");
}
}
//删除第i个节点
public void delete(int i){
if((getLength()>i) && (i>0)){
currentNode = head;
if(i == 1){
head = currentNode.next;
}
else{
for(int j = 1; j<(i-1); j++){
currentNode = currentNode.next;//遍地到要删除节点的前一节点
}
LinkNode tempNode = currentNode.next;
currentNode.next = tempNode.next;
}
}
else{
System.out.println("这个节点不存在");
}
}
public void display(){
currentNode = head;
while(currentNode != null){
System.out.println(currentNode.data.toString());
currentNode = currentNode.next;
}
}
public static void main(String args[]){
LinkList ll = new LinkList(4);
//ll.insert(0,"b");
//ll.insert(1,"b");
//ll.insert(1,"d");
//ll.insert(4,"e");
ll.display();
System.out.println(ll.getLength());
ll.delete(2);
ll.display();
}
}