题目:找出单链表的中间值,朴素的想法是先遍历链表计算出链表总长度,再找中间节点,此方法效率太低。
思路:创建两个指针,一个指针pslow每次往后移动1个位置,另一个pquick移动两个位置,当pquick移动到最后一个元素时,pslow指向的元素就是中间位置。
注意:
1、判断什么时候结束,很重要,pquick移动到最后一个元素就结束了,判断是否是最后一个元素,是通过pquick->next==null,而非pquick==null。
2、若想改变传入函数的指针,必须用引用,否则改变不了。因为,在函数体内,我们只能用指针改变指针指向的内容,而不能改变指针本身。
#include <iostream>
#include<vector>
using namespace std;
typedef struct node
{
node *next;
int data;
node() :next(NULL), data(0){}
}node, *list;
node *change(vector<int> &a)
{
node *list = new node();
node *temp;
node *tail = list;
for (int i = 0; i < a.size(); i++)
{
temp = new node();
temp->data = a[i];
tail->next = temp;
tail = temp;
}
return list;
}
bool move(node * &p)
{
if (p->next == NULL) return false;
if (p->next->next == NULL) return false;
if (p->next->next->next == NULL) return false;
p = p->next->next;
return true;
}
int get(list lis)
{
node *p = lis;
node *q = lis;
p = p->next;
while (move(q))
{
p = p->next;
}
return p->data;
}
int main()
{
vector<int> data = { -2,2,4,6,8};
list lis;
lis = change(data);
cout << get(lis);
system("pause");
return 0;
}