单链表遍历的代码实现
时间: 2024-06-22 21:01:06 浏览: 77
单链表的实现
单链表的遍历通常有两种方式:顺序遍历(也叫前向遍历)和逆序遍历。这里分别给出这两种遍历的代码实现,使用 C++ 语言:
1. **顺序遍历(前向遍历)**:
```cpp
class Node {
public:
int data;
Node* next;
};
// 假设你有一个名为head的链表头指针
void traverseForward(Node* head) {
if (head == nullptr) {
cout << "链表为空" << endl;
} else {
Node* current = head;
while (current != nullptr) {
cout << current->data << " -> ";
current = current->next;
}
cout << "nullptr" << endl; // 输出最后一个节点后停止
}
}
```
2. **逆序遍历**:
```cpp
void traverseReversed(Node* head) {
if (head == nullptr) {
cout << "链表为空" << endl;
} else {
Node* current = head;
Node* previous = nullptr; // 用于存储前一个节点
while (current != nullptr) {
previous = current;
current = current->next;
}
while (previous != nullptr) {
cout << previous->data << " -> ";
previous = previous->next;
}
cout << "nullptr" << endl; // 输出最后一个节点后停止
}
}
```
阅读全文