while循环遍历链表
时间: 2025-06-10 15:46:18 浏览: 15
### 如何使用 `while` 循环遍历链表
在编程中,链表是一种常见的数据结构。为了通过 `while` 循环来遍历链表,通常需要定义一个当前节点变量,并将其初始化为链表头节点。随后,在每次迭代过程中更新该变量指向下一个节点,直到到达链表末尾。
以下是基于单向循环链表的 `while` 循环遍历示例:
#### Python 示例代码
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
# 添加节点到链表末尾
def append(self, data):
new_node = Node(data)
if not self.head: # 如果链表为空
self.head = new_node
self.head.next = self.head # 自己指向自己形成循环
else:
current = self.head
while current.next != self.head: # 找到最后一个节点
current = current.next
current.next = new_node # 新节点连接到最后一个节点之后
new_node.next = self.head # 新节点再连回头部完成闭环
# 使用 while 循环遍历链表
def traverse_with_while(self):
if not self.head: # 判断链表是否为空
print("链表为空。")
return
current = self.head
while True: # 进入无限循环
print(current.data) # 访问当前节点的数据
current = current.next # 移动到下一个节点
if current == self.head: # 当回到头部时退出循环
break
# 测试代码
clist = CircularLinkedList()
clist.append(10)
clist.append(20)
clist.append(30)
print("遍历链表:")
clist.traverse_with_while()
```
#### 解析
- **创建节点类**: 定义了一个简单的 `Node` 类用于存储数据和指向下一节点的引用。
- **构建循环链表**: 在 `CircularLinkedList` 中实现了 `append` 方法,用于将新节点追加至链表末尾并保持其循环特性[^4]。
- **遍历逻辑**: 使用 `while` 循环访问每个节点,当再次返回到链表头节点时停止循环[^1]。
---
#### JavaScript 示例代码
对于 JavaScript 实现,可以参考如下代码片段:
```javascript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class CircularLinkedList {
constructor() {
this.head = null;
}
// 添加节点到链表末尾
append(data) {
const newNode = new Node(data);
if (!this.head) { // 若链表为空,则设置头结点
this.head = newNode;
newNode.next = this.head; // 形成自循环
} else {
let current = this.head;
while (current.next !== this.head) { // 寻找最后一个节点
current = current.next;
}
current.next = newNode; // 将新节点附加到最后
newNode.next = this.head; // 维持循环性质
}
}
// 使用 while 循环遍历链表
traverseWithWhile() {
if (!this.head) { // 处理空链表情况
console.log("链表为空");
return;
}
let current = this.head;
do {
console.log(current.data); // 输出当前节点数据
current = current.next; // 转移到下个节点
} while (current !== this.head); // 返回起点则结束
}
}
// 创建实例并测试
const clist = new CircularLinkedList();
clist.append(5);
clist.append(10);
clist.append(15);
console.log("遍历链表:");
clist.traverseWithWhile();
```
#### 解析
- 上述代码展示了如何利用 `do...while` 或者标准 `while` 来安全地遍历整个循环链表而不陷入死循环[^2]。
---
### 注意事项
- 对于非循环链表(即普通单向或双向链表),只需修改终止条件为检测 `next === null` 即可[^3]。
- 确保在实现过程中考虑边界条件,比如空链表的情况。
---
阅读全文
相关推荐


















