在链表中找出倒数第K个节点

2023-06-26,,

(1)遍历两遍,第一次计算出链表长度n,第二次找到(n-k)个节点,也就是倒数第K个节点。

(2)遍历一遍,定义两个指针,一个指针fast,一个指针slow,都指向头结点,fast指针先向前走K,然后再同时遍历,当fast遍历到最后一个节点时,slow所指向的节点就是倒数第K个节点。

#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("倒数第K个数:%d\n",ret->_value);
   
 
}
int main()
{
    test();
    system("pause");
    return 0;
}

结果:

《在链表中找出倒数第K个节点.doc》

下载本文的Word格式文档,以方便收藏与打印。