求鏈表倒數第幾個節點,倒數幾個節點
使用兩個指標,和判斷一個鏈表是否形成環類似
代碼:
#include <iostream>#include <list>using namespace std;typedef struct node {int data;struct node *next ;}Node,*pNode;void creatNode( pNode &pHead ){bool isFirst=true;pNode p,q;int temp;scanf("%d",&temp);while(temp){p=(pNode)malloc(sizeof(Node));p->data = temp;p->next = NULL;if(isFirst){q=pHead=p;isFirst = false;}else{q->next = p;q = p;}scanf("%d",&temp);}}void print(pNode p){while(p){cout<<p->data << " ";p = p->next;}}pNode printLast(pNode pHead,unsigned int m){if(NULL == pHead || m==0)return NULL ;pNode pAhead = pHead;pNode pBehind = pHead;for(int i=1;i<=m;i++){if(pAhead->next != NULL)pAhead = pAhead->next;elsereturn NULL;}while(pAhead){pAhead = pAhead->next;pBehind = pBehind->next;}return pBehind;}int main(){ pNode pHead=NULL;creatNode(pHead);print(pHead); cout<<endl<< printLast(pHead,2)->data; return 0;}
運行結果:
單鏈表倒數第k個結點
Node* create_Link(int num)
{
Node* head,*p,*q;
p=new Node();
p->data=1;
head=p;
for (int i=2;i<=num;i++)
{
q=new Node();
q->data=i;
p->next=q;
p=q;
}
p=NULL;//最後一個節點指向空
return head;
}
Node* FindK(Node* head,int k)
{
Node* pslow,*pfast;
pslow=pfast=head;
int i=0;
while(i<k)
{
pfast=pfast->next;
i++;
}
while(pfast)
{
pfast=pfast->next;
pslow=pslow->next;
}
return pslow;
}
int _tmain(int argc, _TCHAR* argv[])
{
Node* head = create_Link(10);
Node* kNode=FindK(head,2);
cout<<kNode->data<<endl;
system("pause");
return 0;
}
單鏈表中倒數第k個元素 要:不可以利用鏈表中元素的個數 完整程式
既然不能用鏈表中的元素個數,那就得另想辦法了。
我給你思想吧。程式你自己寫了。
演算法思想:
1、單鏈表如果知道頭結點的指標,那麼可以順著結點的指標域一直找下去來遍曆元素。
2、那麼我們可以這樣,從第一個結點開始取值,然後判斷這個結點到單鏈表結束是不是倒數第k個,如果不是,繼續往下取第二個結點值,然後判斷這個結點到單鏈表結束是不是倒數第k個,後續依次。(其中要求判斷的是個迴圈)
還有一種演算法,最笨的 就是鏈錶轉換成順序表,不過這個順序表的空間可是個問題哦。
程式我不想代勞了。你自己練習吧。