摘要:
其实还是要对单链表的操作熟悉, 思路上来说, 还是使用双指针的思路
要求:
- 单链表
- 找出倒数第N个元素
- 只能用一次遍历
思考:
- 如果没有限制只能一次遍历, 那么最简单的做法,就是先遍历一次找到链表长度, 然后就可以找到要遍历到第几个元素
- 一次遍历的话, 可以用两个指针, 第一个指针先前进N步, 第二个指针再开始同步前进, 这样当第一个指针前进到结尾时, 第二个指针就是倒数第N个元素
题解:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
Node* next;
Node():data(-1),next(nullptr)
{}
Node(int value):data(value),next(nullptr)
{}
};
struct List {
Node* head;
Node* tail;
List():head(nullptr),tail(nullptr)
{}
};
void ShowList(List* list) {
if (!list) {
return;
}
if (!list->head) {
return;
}
Node* node = list->head;
while (node) {
printf("%d\n", node->data);
node = node->next;
}
}
Node* find(List* list, int n) {
if (!list) {
return nullptr;
}
if (!list->head) {
return nullptr;
}
Node* first = list->head;
Node* sencod = list->head;
for (int i = 0; i < n; i++) {
if (!first->next) {
return nullptr;
}
first = first->next;
}
while (first) {
first = first->next;
sencod = sencod->next;
}
}
int main(int argc, const char** argv) {
List* list = new List;
Node* n1 = new Node(1);
Node* n2 = new Node(2);
Node* n3 = new Node(3);
Node* n4 = new Node(4);
Node* n5 = new Node(5);
list->head = n1;
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
// ShowList(list);
Node* v = find(list, 2);
printf("%d\n", v->data);
return 0;
}