设计一个算法,找到链表的倒数第m个元素,假设最后一个元素为倒数第0个。算法的复杂度为n。
方法一:遍历链表,得到链表的长度,再找到链表的第n-m个元素即可(如果链表的长度知道就直接找第n-m个元素)。
方法二:双指针查找。用两个指针p1、p2,开始都指向头节点。p1先移动,当p1和p2的距离为m时,两个指针一起移动,当p1移动到尾节点时,此时p2指向的节点就是要找的节点。
具体代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
Node* pNext;
}*pNode;
pNode InitNode()
{
pNode pHead=(pNode)malloc(sizeof(Node));
pHead->pNext=NULL;
return pHead;
}
void CreateListNode(pNode pHead,int nodeNum)
{
pNode pTail=pHead;
for (int i=0;i<nodeNum;i++)
{
pNode pCur=(pNode)malloc(sizeof(Node));
pCur->data=i+1;
pTail->pNext=pCur;
pCur->pNext=NULL;
pTail=pCur;
}
}
void ShowNodeData(pNode pHead)
{
while(pHead->pNext)
{
printf("%d\n",pHead->pNext->data);
pHead=pHead->pNext;
}
}
//找到链表的第m个元素
int GetTheData(pNode pHead,int m)
{
int i=0;
pNode pTail=pHead;
while (pTail->pNext)
{
i++;
if (i==m)
{
return pTail->pNext->data;
}
pTail=pTail->pNext;
}
}
//第一种方法
int GetTheDataByOne(pNode pHead,int m)
{
int n=0;
pNode pCur=pHead;
while (pCur->pNext)
{
n++; //先得到链表的长度
pCur=pCur->pNext;
}
return GetTheData(pHead,n-m);
}
//第二种方法
int GetTheDataBySecond(pNode pHead,int m)
{
pNode pFirst=pHead,pSecond=pHead;
int instance=0;
while (pFirst->pNext!=NULL) //p1移动到最后一个节点时,循环结束
{
if (instance==m)
{
pFirst=pFirst->pNext;
pSecond=pSecond->pNext;
}
else
{
pFirst=pFirst->pNext;
instance++;
}
}
return pSecond->data;
}
int _tmain(int argc, _TCHAR* argv[])
{
Node*pHead=InitNode();
CreateListNode(pHead,8);
ShowNodeData(pHead);
printf("输入倒数第几个元素");
int iNum=0;
scanf("%d",&iNum);
printf("方法一的结果是:%d\n",GetTheDataByOne(pHead,iNum));
printf("方法二的结果是:%d\n",GetTheDataBySecond(pHead,iNum));
return 0;
}
230



被折叠的 条评论
为什么被折叠?



