在单次遍历中查找 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
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP