链接点
- 链接点中包含一个数据域和一个指针域,其中数据域用来包装数据,而指针域用来指向下一个链接点
public class Link{
private int data;
private Link next;
public Link(int data){
this.data=data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Link getNext() {
return next;
}
public void setNext(Link next) {
this.next = next;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
实现链表
- 在插入节点到制定位置的部分,为什么只循环到pos-1
假如在下标2的位置插入数据,我们只需要找到1的下标在其后面插入数据即可。
public class LinkList{
private Link first;
public void insert(int value){
Link lnk = new Link(value);
if(first == null){
first = lnk;
}else{
lnk.setNext(first);
first = lnk;
}
}
public void display(){
Link current = first;
while(current != null){
System.out.println(current.getData());
current = current.getNext();
}
}
public Link find(int key){
Link current = first;
while(current.getData() != key){
if(current.getNext() == null){
return null;
}
current = current.getNext();
}
}
public void insert(int value,int pos){
if(pos == 0){
insert(value);
}else{
Link current = first;
for(int i=0;i<pos-1;i++){
current = current.getNext();
}
Link lnk = new Link(value);
lnk.setNext(current.getNext());
current.setNext(lnk);
}
}
public void delete(int key){
Link current = first;
Link ago = first;
while(current.getData() != key){
if(current.getNext() == null){
return;
}else{
ago = current;
current = current.getNext();
}
}
if(current == first){
first = first.getNext();
}else{
ago.setNext(current.getNext());
}
}
}