溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在鏈表中找出倒數(shù)第K個(gè)節(jié)點(diǎn)

發(fā)布時(shí)間:2020-06-16 14:54:43 來源:網(wǎng)絡(luò) 閱讀:285 作者:秋笙夏笛 欄目:編程語言

(1)遍歷兩遍,第一次計(jì)算出鏈表長(zhǎng)度n,第二次找到(n-k)個(gè)節(jié)點(diǎn),也就是倒數(shù)第K個(gè)節(jié)點(diǎn)。

(2)遍歷一遍,定義兩個(gè)指針,一個(gè)指針fast,一個(gè)指針slow,都指向頭結(jié)點(diǎn),fast指針先向前走K,然后再同時(shí)遍歷,當(dāng)fast遍歷到最后一個(gè)節(jié)點(diǎn)時(shí),slow所指向的節(jié)點(diǎn)就是倒數(shù)第K個(gè)節(jié)點(diǎn)。

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
 
struct Listnode
{
    int _value;
    Listnode* _next;
};
void Init(Listnode*& head)
{
    Listnode* cur =head;
    if(cur==NULL)
    {
        cur=(Listnode*)malloc(sizeof(Listnode));
        cur->_next=NULL;
        cur->_value=0;
    }
    head=cur;
}
 
void push(Listnode*& head,int value)
{
    Listnode* cur =head;
 
        while(cur->_next)
        {
            cur=cur->_next;
        }
        Listnode* tmp=NULL;
        tmp=(Listnode*)malloc(sizeof(Listnode));
        tmp->_next=NULL;
        tmp->_value=value;
        cur->_next=tmp;
     
         
 
}
void pop(Listnode* head)
{
    Listnode* cur=head;
    Listnode* prev=NULL;
    while(cur->_next!=NULL)
    {
        prev=cur;
        cur=cur->_next;
    }
    prev->_next=NULL;
    free(cur);
    cur=NULL;
}
void print(Listnode* head)
{
    Listnode* cur=head;
    while(cur)
    {
        printf("%d\n",cur->_value);
        cur=cur->_next;
    }
}
Listnode* Find(Listnode* head,int k)
{
    assert(head);
	assert(k>0);
	Listnode* slow=head;
	Listnode* fast=head;
	while(k--)
	{
		fast=fast->_next;
	}
	while(fast)
	{
		slow=slow->_next;
		fast=fast->_next;
	}
	return slow;

}

void test()
{
    Listnode* head=NULL;
    Init(head);
    push(head,1);
    push(head,2);
    push(head,3);
    /*pop(head);*/
     print(head);
	Listnode* ret=Find(head,2);
	printf("倒數(shù)第K個(gè)數(shù):%d\n",ret->_value);
   
 
}
int main()
{
    test();
    system("pause");
    return 0;
}

結(jié)果:

在鏈表中找出倒數(shù)第K個(gè)節(jié)點(diǎn)

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI