建立结点
package com.huachao;
private int data;
private LinkedListNode link;
public LinkedListNode getLink() {
return link;
}
public void setLink(LinkedListNode link) {
this.link = link;
}
LinkedListNode(int data){
this.data = data;
}
public int getData(){
return data;
}
public int setData(){
return data;
}
}
链表的创建插入和删除
package com.huachao;
import java.util.Scanner;
public class LinkedList {
LinkedListNode head;
private int length;
public int getlength(){
return length;
}
void create(){
Scanner in = new Scanner(System.in);
head = new LinkedListNode(in.nextInt());
length++;
LinkedListNode p = head;
int data;
while((data = in.nextInt() )!= -1){
LinkedListNode q = new LinkedListNode(data);
p.setLink(q);
p = q;
length++;
}
in.close();
}
boolean insert(int pos, int data){
int i = 0;
LinkedListNode p = head;
LinkedListNode q;
if(pos >= length){
System.out.print("dd");
return false;
}else{
while(i<pos){
++i;
p = p.getLink();
}
q =p.getLink() ;
p.setLink( new LinkedListNode(data) );
p = p.getLink();
p.setLink(q);
}
return true;
}
boolean delete(int pos){
int j = 0;
LinkedListNode p = head;
while(j<pos){
++j;
p = p.getLink();
}
p.setLink(p.getLink().getLink());
return true;
}
void print(){
LinkedListNode p = head;
while(p.getLink() != null){
System.out.print(p.getData() + " ");
p = p.getLink();
}
System.out.print(p.getData() + " ");
//System.out.print("length" + length);
}
}
测试:
package com.huachao;
public class Test {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.create();
l.print();
l.insert(1, 2);
//System.out.println(l.getlength());
l.print();
l.delete(1);
l.print();
}
}