您的位置:首页 > 理论基础 > 数据结构算法

链接点以及链表实现

2016-11-02 14:12 267 查看

链接点

链接点中包含一个数据域和一个指针域,其中数据域用来包装数据,而指针域用来指向下一个链接点

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;
}
}


实现链表

在插入节点到制定位置的部分,为什么只循环到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());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 数据结构
相关文章推荐