6. 链结点¶
6.1. 链结点¶
在本模块中,我们将介绍 链结点 的概念。 链结点含有一个存放某种值的字段,以及一个指向另一个链结点的指针。 稍后你将学习由链结点构成的 链表 。 现在,我们只把它们当作把一些对象连接在一起的简单方式。
下面是一个基本 link 对象的类定义。
注意, next 字段引用的是另一个 link 对象,而 data 字段的类型为 Object 。
这表示我们并不关心在 link 结点的数据字段中到底存储什么东西。
class Link {
public Link next; //Point to next node in list
public Object data; //Value for this node
//Constructors
public Link(Object dataIn, Link nextIn) {
this.data = dataIn;
this.next = nextIn;
}
public Link(Link nextIn) {
this.data = null;
this.next = nextIn;
}
Object getData() { // Return the data field
return data;
}
void setData(Object newData) { // Set the data field
data = newData;
}
Link getNext() { // Return the next field
return next;
}
void setNext(Link newNext) { // Set the next field
next = newNext;
}
}
class Link {
public Link next; //Point to next node in list
public Object data; //Value for this node
//Constructors
public Link(Object dataIn, Link nextIn) {
this.data = dataIn;
this.next = nextIn;
}
public Link(Link nextIn) {
this.data = null;
this.next = nextIn;
}
Object getData() { // Return the data field
return data;
}
void setData(Object newData) { // Set the data field
data = newData;
}
Link getNext() { // Return the next field
return next;
}
void setNext(Link newNext) { // Set the next field
next = newNext;
}
}
下面我们来看一些示例,说明如何使用 link 结点把链串接起来。
我们要如何在一开始就建立起这条链呢?
下面是一道练习操作链结点的习题。

