//找链表的中间结点
/*
已知单链表L,编写算法找出该链表的中间位置的结点。
思考:
1、一种想法就是从头遍历到尾部,记录长度。随后再次遍历一次,直到长度的二分之一即找到。时间复杂度为O(3n/2)
2、另一种想法:设置快慢指针,快指针一次走两步,慢指针一次走一步,当快指针走到NULL的时候,慢指针的位置就是链表的中间位置
本程序使用第二种想法
*/
#include <iostream>
#include <string>
using namespace std;
int L_length = 0;
template<class T>
struct Node {
T value;
Node *next;
Node() {
next = NULL;
}
Node(const T &data) {
value = data;
next = NULL;
}
};
template<class T>
void PushinList(Node<T>* &L, const T &t) {
Node<T> *n = new Node<T>(t);
n->next = L->next;
L->next = n;
L_length++;
}
template<class T>
void PrintList(const Node<T>* L) {
cout << "打印链表:";
for (Node<T>* p = L->next; p != NULL; p = p->next) cout << p->value << " ";
cout << endl;
}
template<class T>
Node<string>* GetMiddle(const Node<T>* L) {
Node<string> *p_fast, *p;
p = p_fast = L->next;
while (p_fast) {
p_fast = p_fast->next;
if (p_fast) p_fast = p_fast->next;
else break;
p = p->next;
}
return p;
}
int main(void) {
Node<string>* L = new Node<string>();
string str;
cout << "创建链表(以-1结尾):";
while (cin >> str && str != "-1")
PushinList(L, str);
PrintList(L);
Node<string>* p = GetMiddle(L);
cout << "中部节点为" << p->value << endl;
system("pause");
return 0;
}
/*
样例输入:
a b c d e f g -1
a b c d e f -1
样例输出:
d
c
*/