408真题2009第42题
1 #include<iostream> 2 using namespace std; 3 struct node { 4 int data; 5 node* next; 6 7 }; 8 int main() { 9 int d; 10 node* start=NULL, * end = NULL, * t = NULL; 11 cin >> d; 12 while (d < 100) { 13 if (start == NULL) { 14 t = (node*)malloc(sizeof(node)); 15 t->next = NULL; 16 t->data = d; 17 start = t; 18 end = start; 19 20 21 } 22 else { 23 t = (node*)malloc(sizeof(node)); 24 t->data = d; 25 t->next = NULL; 26 end->next = t; 27 end = t; 28 } 29 cin >> d; 30 } 31 cout << "请输入您要查询倒数第几个节点?" << endl; 32 int lastNode; 33 cin >> lastNode; 34 node* first=start, * second = NULL; 35 while (first->next != NULL) { 36 for (int i = 0; i < lastNode - 1&&second == NULL; i++) { 37 first = first->next; 38 } 39 if(second==NULL) 40 second = start; 41 else 42 { 43 second = second->next; 44 first = first->next; 45 } 46 47 48 } 49 cout << second->data; 50 return 0; 51 }
时间复杂读O(n);

浙公网安备 33010602011771号