揭开链表的真面目

Java旅途

一 单向链表

1.2 实现单向链表的存储等操作

``````public class Node {

// 数据域
public long data;
// 指针域
public Node next;

public Node(long value){
this.data = value;
}
}``````

1.2.1 插入一个节点

``````public class LinkList {

private Node head;
/**
* 在头节点之后插入一个节点
*/
public void insertFirst(long value){
Node node = new Node(value);
node.next = head;
head = node;
}
}``````

1.2.2 头结点后删除一个结点

``````public Node deleteFirst(){
Node tmp = head;
head = tmp.next;
return tmp;
}``````

1.2.3 根据数据域查找结点

``````public Node find(long value){

Node current = head;
while (current.data != value){
if(current.next == null){
return null;
}
current = current.next;
}
return current;
}``````

1.2.4 根据数据与删除结点

``````public Node delete(int value){
Node current = head;
// 当前结点的前一个结点
Node pre = head;
while (current.data != value){
if(current.next == null){
return null;
}
pre = current;
current = current.next;
}
if(current == head){
head = head.next;
}else{
pre.next = current.next;
}
return current;
}``````

二 双端链表

2.2 实现双端链表的存储等操作

2.2.1 从头部插入结点

``````public class FirstLastLinkList {

private Node first;
private Node last;
/**
* 在头结点之后插入一个节点
*/
public void insertFirst(long value){
Node node = new Node(value);
if(first == null){
last = node;
}
node.next = first;
first = node;
}
}``````

2.2.2 从尾部插入结点

``````public void insertLast(long value){
Node node = new Node(value);
if(first == null){
first = node;
}else{
last.next = node;
}
last = node;
}``````

2.2.3 从头部进行删除

``````public Node deleteFirst(){

Node tmp = first;
if(first.next == null){
last = null;
}
first = tmp.next;
return tmp;
}``````

三 双向链表

3.2 实现双向链表的存储等操作

``````public class Node {

// 数据域
public long data;
// 后一个结点指针域
public Node1 next;
// 前一个结点指针域
public Node prev;

public Node(long value){
this.data = value;
}
}``````

3.2.1 从头部插入结点

``````public class DoubleLinkList {

private Node first;
private Node last;

/**
* 在头结点之后插入一个节点
*/
public void insertFirst(long value){
Node node = new Node(value);
if(first == null){
last = node;
} else{
first.prev = node;
}
node.next = first;
first = node;
}
}``````

3.2.2 从尾部插入结点

``````public void insertLast(long value){
Node node = new Node(value);
if(first == null){
first = node;
}else{
last.next = node;
node.prev = last;
}
last = node;
}``````

3.2.3 从头部删除结点

``````public Node deleteFirst(){

Node tmp = first;
if(first.next == null){
last = null;
}else{
first.next.prev = null;
}
first = tmp.next;
return tmp;
}``````

3.2.4 从尾部删除结点

``````public Node deleteLast(){

Node tmp = last;
if(first.next == null){
first = null;
}else{
last.prev.next = null;
}
last = last.prev;
return last;
}``````

点关注、不迷路

Java进阶路线
java技术分享，从小白到巨人的成长过程
1.1k 声望
6.1k 粉丝
0 条评论