遍历链表时跳出循环的依据

解决链表相关的算法题时,在循环的判断语句中,选择pNode==nullptr 与 pNode->next==nullptr的问题上举棋不定,处理起来很不顺心。

所以,记录下 选择pNode==nullptr 还是 pNode->next==nullptr 的依据

下面以一道算法题展开讲解,题目为 从尾到头打印链表

链表节点定义如下:

struct ListNode
{
    int m_nKey;
    ListNode * m_pNext;
}

思路为:从头到尾遍历每一个节点,将每一个节点压入栈中,然后,依次打印栈顶、弹出栈顶元素,直到栈为空。

这里就涉及到遍历每一个节点,在循环的判断语句中 选择pNode==nullptr 还是 pNode->next==nullptr 的问题就来了

选择依据其实很简单,就是最后的pNode节点是否需要在循环体中被处理

在本例子中,利用循环体处理压栈操作,显然,最后一个节点是需要被压栈处理的,所以选择pNode==nullptr

实现代码如下:

void PrintListReversingly_Iteratively(ListNode * pHead)
{
    std::stack<ListNode*> nodes;
    
    ListNode * pNode = pHead;
    while(pNode != nullptr){
        nodes.push(pNode);
        pNode = pNode->m_pNext;
    }
    while(!nodes.empty()){
        pNode = nodes.top();
        cout<<pNode->m_nKey<<"    ";
        nodes.pop();
    }
}

再举例,如何获取指向链表最后一个节点的指针?

显然也是利用循环体,在循环体中切换到下一节点,我们不想到最后一个节点时还切换到下一个节点,所以pNode->next==nullptr

ListNode * pNode = pHead;
while(pNode->next==nullptr){
    pNode = pNode->m_pNext;
}

这样,在退出循环体后,pNode指向链表的最后一个节点

 

结论:

在遍历链表时,若最后一个节点需要在循环体中被处理,选择pNode==nullptr 

                         若最后一个节点不需要在循环体中被处理,选择pNode->next==nullptr

而无论选择哪一种,由于是遍历,循环体中都是采用pNode = pNode->m_pNext;

 

### 如何使用 `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]。 - 确保在实现过程中考虑边界条件,比如空链表的情况。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值