在C ++中单遍历查找链表的倒数第二个节点
现在,我们将看到如何获取链表中的倒数第二个元素。假设元素很少,例如[10、52、41、32、69、58、41],倒数第二个元素是58。
为了解决这个问题,我们将使用两个指针,一个指针指向当前节点,另一个指针指向当前位置的上一个节点,然后我们将移动直到当前下一个为空,然后简单地返回上一个节点。
示例
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
};
void prepend(Node** start, int new_data) {
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = NULL;
if ((*start) != NULL){
new_node->next = (*start);
*start = new_node;
}
(*start) = new_node;
}
int secondLastElement(Node *start) {
Node *curr = start, *prev = NULL;
while(curr->next != NULL){
prev = curr;
curr = curr->next;
}
return prev->data;
}
int main() {
Node* start = NULL;
prepend(&start, 15);
prepend(&start, 20);
prepend(&start, 10);
prepend(&start, 9);
prepend(&start, 7);
prepend(&start, 17);
cout << "Second last element is: " << secondLastElement(start);
}输出结果
Second last element is: 20
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿