注意:
无论采用什么思路,编程时都要考虑,链表结点个数不足4个的情况。
思路1:
先找到最后一个元素,然后再从头扫描一遍,判断该元素的之后的第三个结点是否是最后一个结点。O(4n)=O(n)。比较粗糙的方法。
思路2:
快慢指针。先让快指针先走4步,找到第四个结点。然后让快慢指针同时走,每次一步。当快指针走到最后一个结点时,慢指针指向倒数第4个元素。
思路3:
建立一个含有4个元素的循环队列(数组来模拟),扫描一遍队列,让他们不断的进入循环队列中,当最后一个结点进入循环队列后,队列的下一个元素则是倒数第4个结点。
我采用思路2来实现。
// LinkTable.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//链表的结构体
struct node
{
char val;
node * next;
};
//2,找第4个结点
struct node * create( string & str_link )
{
int len = str_link.length();
struct node * phead = new node(); //带有表头的链表,表头中不存储任何元素
struct node * preNode = phead;
for( int i=0; i<len; i++ )
{
struct node * pNode = new node();
pNode->val = str_link[i];
pNode->next = NULL;
preNode->next = pNode;
preNode = pNode;
}
return phead;
}
void out_link( struct node * phead )
{
if( phead == NULL )
return;
struct node * pNode = phead->next;
while( pNode )
{
cout <<pNode->val;
pNode = pNode->next;
}
cout << endl;
}
struct node * find_third_node( struct node * phead )
{
if( !phead ) return NULL;
//快指针先走4步
struct node *pFast = phead;
struct node *pSlow = phead;
int num =4;
while(num--)
{
pFast = pFast->next;
if(!pFast) //还没走完就没了
{
return NULL;
break;
}
}
//快慢指针一起走
while(pFast)
{
pFast = pFast->next;
pSlow = pSlow->next;
}
return pSlow;
}
void test()
{
string str;
cin >> str;
struct node *phead = create( str );
cout << "The Link is : ";
out_link( phead );
struct node *pNode = find_third_node( phead );
if( pNode )
cout << "The last_third node's value is : " << pNode->val <<endl;
else
cout << "The number of node is less than 4." << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test();
return 0;
}